@workingpayload/agent-skills 1.0.1 → 2.0.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/APIForge/skill.md +165 -0
- package/AccessPlus/skill.md +136 -0
- package/AlgoMaster/skill.md +125 -0
- package/Architekt AI/skill.md +140 -0
- package/AuthCraft/skill.md +144 -0
- package/AutoScriptor/skill.md +137 -0
- package/BoilerCore/skill.md +136 -0
- package/BugHunter Pro/skill.md +133 -0
- package/ChangeScribe/skill.md +113 -0
- package/CodeSage/skill.md +163 -0
- package/CommitCraft/skill.md +113 -0
- package/CoverageMax/skill.md +161 -0
- package/CronGenius/skill.md +157 -0
- package/DataPolish/skill.md +142 -0
- package/DataWeaver/skill.md +151 -0
- package/DockMaster/skill.md +158 -0
- package/DocuGenie/skill.md +138 -0
- package/EdgeGuard/skill.md +160 -0
- package/EnvWizard/skill.md +156 -0
- package/ErrorMedic/skill.md +152 -0
- package/FeatureSmith/skill.md +139 -0
- package/FlexiLayout/skill.md +144 -0
- package/FlowTester/skill.md +154 -0
- package/FunctionForge/skill.md +136 -0
- package/InputShield/skill.md +144 -0
- package/IssueForge/skill.md +148 -0
- package/KubeCrafter/skill.md +149 -0
- package/LogicLens/skill.md +132 -0
- package/MockSmith/skill.md +146 -0
- package/ModelSensei/skill.md +138 -0
- package/PRMentor/skill.md +103 -0
- package/PerfDetective/skill.md +90 -0
- package/PipelinePro/skill.md +146 -0
- package/PolyglotShift/skill.md +94 -0
- package/PromptForge/skill.md +118 -0
- package/QueryPulse/skill.md +123 -0
- package/README.md +416 -329
- package/ReadMeCraft/skill.md +127 -0
- package/RefactorX/skill.md +84 -0
- package/RenderBoost/skill.md +148 -0
- package/SEOMancer/skill.md +156 -0
- package/ScrapeMaster/skill.md +157 -0
- package/SecretSniffer/skill.md +123 -0
- package/SecureScan/skill.md +130 -0
- package/ServiceSplitter/skill.md +153 -0
- package/SpeedSmith/skill.md +155 -0
- package/StackWise/skill.md +155 -0
- package/TaskOrchestrator/skill.md +135 -0
- package/TestCrafter/skill.md +158 -0
- package/TraceMind/skill.md +143 -0
- package/UISmith/skill.md +131 -0
- package/bin/cli.js +377 -0
- package/extension-extender/SKILL.md +122 -0
- package/fastapi-furious/SKILL.md +148 -0
- package/package.json +41 -32
- package/python-master/SKILL.md +108 -0
- package/react-ranger/SKILL.md +93 -0
- package/scripts/build_index.py +282 -0
- package/scripts/doctor.py +541 -0
- package/scripts/install.py +397 -0
- package/scripts/route.py +348 -0
- package/scripts/score.py +355 -0
- package/scripts/test_skill.py +473 -0
- package/scripts/validate.py +254 -0
- package/skills-routing.json +1131 -0
- package/skills.json +3261 -0
- package/cli.js +0 -181
- package/skills/APIForge/skill.md +0 -32
- package/skills/AccessPlus/skill.md +0 -32
- package/skills/AlgoMaster/skill.md +0 -32
- package/skills/Architekt AI/skill.md +0 -32
- package/skills/AuthCraft/skill.md +0 -32
- package/skills/AutoScriptor/skill.md +0 -32
- package/skills/BoilerCore/skill.md +0 -32
- package/skills/BugHunter Pro/skill.md +0 -32
- package/skills/ChangeScribe/skill.md +0 -32
- package/skills/CodeSage/skill.md +0 -32
- package/skills/CommitCraft/skill.md +0 -32
- package/skills/CoverageMax/skill.md +0 -32
- package/skills/CronGenius/skill.md +0 -32
- package/skills/DataPolish/skill.md +0 -32
- package/skills/DataWeaver/skill.md +0 -32
- package/skills/DockMaster/skill.md +0 -32
- package/skills/DocuGenie/skill.md +0 -32
- package/skills/EdgeGuard/skill.md +0 -32
- package/skills/EnvWizard/skill.md +0 -32
- package/skills/ErrorMedic/skill.md +0 -32
- package/skills/Extension-Extender/SKILL.md +0 -41
- package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
- package/skills/Fastapi-Furious/README.md +0 -16
- package/skills/Fastapi-Furious/SKILL.md +0 -37
- package/skills/FeatureSmith/skill.md +0 -32
- package/skills/FlexiLayout/skill.md +0 -32
- package/skills/FlowTester/skill.md +0 -32
- package/skills/FunctionForge/skill.md +0 -32
- package/skills/InputShield/skill.md +0 -32
- package/skills/IssueForge/skill.md +0 -32
- package/skills/KubeCrafter/skill.md +0 -32
- package/skills/LogicLens/skill.md +0 -32
- package/skills/MockSmith/skill.md +0 -32
- package/skills/ModelSensei/skill.md +0 -32
- package/skills/PRMentor/skill.md +0 -32
- package/skills/PerfDetective/skill.md +0 -32
- package/skills/PipelinePro/skill.md +0 -32
- package/skills/PolyglotShift/skill.md +0 -32
- package/skills/PromptForge/skill.md +0 -32
- package/skills/Python-Master/README.md +0 -11
- package/skills/Python-Master/SKILL.md +0 -37
- package/skills/QueryPulse/skill.md +0 -32
- package/skills/React-Ranger/README.md +0 -17
- package/skills/React-Ranger/SKILL.md +0 -37
- package/skills/ReadMeCraft/skill.md +0 -32
- package/skills/RefactorX/skill.md +0 -32
- package/skills/RenderBoost/skill.md +0 -32
- package/skills/SEOMancer/skill.md +0 -32
- package/skills/ScrapeMaster/skill.md +0 -32
- package/skills/SecretSniffer/skill.md +0 -32
- package/skills/SecureScan/skill.md +0 -32
- package/skills/ServiceSplitter/skill.md +0 -32
- package/skills/SpeedSmith/skill.md +0 -32
- package/skills/StackWise/skill.md +0 -32
- package/skills/TaskOrchestrator/skill.md +0 -32
- package/skills/TestCrafter/skill.md +0 -32
- package/skills/TraceMind/skill.md +0 -32
- package/skills/UISmith/skill.md +0 -32
- /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: stackwise
|
|
3
|
+
description: Advises on technology stack selection, evaluates library trade-offs, and produces Architecture Decision Records (ADRs). Use when asked to choose a framework, compare libraries, evaluate tech stack options, or document architectural decisions with rejected alternatives.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# StackWise
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Produces structured technology evaluations that account for team context, project constraints, and long-term maintainability. Output format is an Architecture Decision Record (ADR) with a scored evaluation rubric, library health metrics, and explicit documentation of rejected alternatives. No generic "it depends" answers — every recommendation is justified with concrete criteria.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Requirements Gathering
|
|
15
|
+
|
|
16
|
+
Before evaluating options, establish:
|
|
17
|
+
|
|
18
|
+
**Functional requirements**:
|
|
19
|
+
- What does the technology need to do? (e.g., "serve 10k req/s REST API", "render server-side HTML with dynamic data", "run ML inference on edge devices")
|
|
20
|
+
- What integrations are mandatory? (existing DBs, auth providers, cloud platform)
|
|
21
|
+
- What data/traffic scale is expected at launch and in 2 years?
|
|
22
|
+
|
|
23
|
+
**Non-functional constraints**:
|
|
24
|
+
- Team language/ecosystem familiarity (don't recommend Rust to a Python-only team without explicit buy-in)
|
|
25
|
+
- Deployment target: serverless, containers (Kubernetes), PaaS, edge runtime
|
|
26
|
+
- Licensing constraints: AGPL/GPL incompatibility with proprietary codebase?
|
|
27
|
+
- Compliance: HIPAA, PCI-DSS, GDPR — some require specific data handling capabilities
|
|
28
|
+
- Time to first production: weeks vs. months affects acceptable learning curve
|
|
29
|
+
|
|
30
|
+
**Team context**:
|
|
31
|
+
- Team size and experience level
|
|
32
|
+
- Existing stack to minimize cognitive overhead ("boring technology" preference)
|
|
33
|
+
- Open source vs. commercial support appetite
|
|
34
|
+
|
|
35
|
+
### 2. Evaluation Rubric
|
|
36
|
+
|
|
37
|
+
Score each candidate (1–5 per criterion) with weights adjusted to project context:
|
|
38
|
+
|
|
39
|
+
| Criterion | Weight (default) | Notes |
|
|
40
|
+
|-----------|-----------------|-------|
|
|
41
|
+
| Ecosystem maturity | 20% | Years in production, major adopters, LTS policy |
|
|
42
|
+
| Performance fit | 20% | Benchmarks relevant to the workload type |
|
|
43
|
+
| Developer experience | 15% | TypeScript types, documentation quality, error messages |
|
|
44
|
+
| Library health | 15% | See Section 3 |
|
|
45
|
+
| Operational complexity | 15% | Deployment, monitoring, debugging tooling |
|
|
46
|
+
| Community & support | 10% | GitHub stars trend, Stack Overflow activity, commercial support availability |
|
|
47
|
+
| Migration cost | 5% | Cost to switch away if the choice is wrong |
|
|
48
|
+
|
|
49
|
+
Weighted score = sum of (score × weight). Document numerical scores, not just opinions.
|
|
50
|
+
|
|
51
|
+
### 3. Library Health Metrics
|
|
52
|
+
|
|
53
|
+
For every candidate library, check:
|
|
54
|
+
|
|
55
|
+
| Metric | Tool / Source | Threshold |
|
|
56
|
+
|--------|--------------|-----------|
|
|
57
|
+
| Release recency | GitHub releases | Last release < 12 months |
|
|
58
|
+
| Issue response time | GitHub Insights | Median < 14 days |
|
|
59
|
+
| Open CVEs | `npm audit` / `pip-audit` / OSV.dev | Zero critical/high unpatched CVEs |
|
|
60
|
+
| npm weekly downloads | npmjs.com stats | > 100k/week for production dependency |
|
|
61
|
+
| PyPI download trend | pypistats.org | Stable or growing 6-month trend |
|
|
62
|
+
| Dependents count | GitHub "Used by" | Proxy for ecosystem lock-in risk |
|
|
63
|
+
| Bus factor | git log analysis | > 3 regular contributors |
|
|
64
|
+
| License | SPDX identifier | Compatible with project license (MIT/Apache-2.0 preferred) |
|
|
65
|
+
|
|
66
|
+
Flag libraries with: single maintainer, no releases in 18+ months, high CVE backlog, or license mismatch.
|
|
67
|
+
|
|
68
|
+
### 4. Technology-Specific Comparison Patterns
|
|
69
|
+
|
|
70
|
+
**Frontend framework selection** (React vs. Vue vs. Svelte vs. SolidJS):
|
|
71
|
+
- Evaluate: bundle size, SSR/SSG capabilities, TypeScript quality, ecosystem (component libraries, state management), hiring pool.
|
|
72
|
+
- Key differentiators: React = largest ecosystem; Svelte/Solid = smaller bundles; Vue = gentler learning curve.
|
|
73
|
+
|
|
74
|
+
**Backend framework selection** (Express vs. Fastify vs. NestJS vs. Hono for Node; FastAPI vs. Django vs. Flask for Python):
|
|
75
|
+
- Evaluate: throughput benchmarks (TechEmpower), built-in validation, OpenAPI generation, middleware ecosystem.
|
|
76
|
+
- Key differentiators: Fastify > Express on throughput; NestJS adds structure but heavier; FastAPI = auto-OpenAPI + async.
|
|
77
|
+
|
|
78
|
+
**Database selection** (PostgreSQL vs. MySQL vs. MongoDB vs. DynamoDB vs. CockroachDB):
|
|
79
|
+
- Evaluate: ACID guarantees, query flexibility, horizontal scaling model, managed cloud options.
|
|
80
|
+
- Default: PostgreSQL unless workload specifically requires document flexibility (MongoDB), global horizontal scale (CockroachDB/Spanner), or serverless cost model (DynamoDB).
|
|
81
|
+
|
|
82
|
+
**Caching layer** (Redis vs. Memcached vs. DragonflyDB):
|
|
83
|
+
- Redis: persistence, pub/sub, Lua scripting, cluster mode — default choice.
|
|
84
|
+
- Memcached: simpler, marginally faster for pure string cache — only if Redis features unneeded.
|
|
85
|
+
- DragonflyDB: Redis-compatible, multi-threaded, lower memory — evaluate if Redis memory cost is a bottleneck.
|
|
86
|
+
|
|
87
|
+
### 5. ADR Output Format
|
|
88
|
+
|
|
89
|
+
Produce every recommendation as an ADR:
|
|
90
|
+
|
|
91
|
+
```markdown
|
|
92
|
+
# ADR-001: API Framework Selection for Payment Service
|
|
93
|
+
|
|
94
|
+
## Status
|
|
95
|
+
Accepted | 2024-03-15
|
|
96
|
+
|
|
97
|
+
## Context
|
|
98
|
+
We are building a payment processing microservice in Python expected to handle
|
|
99
|
+
5,000 req/s. The team has strong Python experience. We need auto-generated OpenAPI
|
|
100
|
+
docs and async support for calling downstream payment gateways.
|
|
101
|
+
|
|
102
|
+
## Decision
|
|
103
|
+
Use **FastAPI** with **Uvicorn** (ASGI) as the API framework.
|
|
104
|
+
|
|
105
|
+
## Evaluation
|
|
106
|
+
|
|
107
|
+
| Criterion | FastAPI (score) | Django REST (score) | Flask (score) |
|
|
108
|
+
|---------------------|----------------|---------------------|---------------|
|
|
109
|
+
| Ecosystem maturity | 4 | 5 | 5 |
|
|
110
|
+
| Performance fit | 5 | 3 | 3 |
|
|
111
|
+
| Developer experience| 5 | 4 | 3 |
|
|
112
|
+
| Library health | 5 | 5 | 4 |
|
|
113
|
+
| Operational complexity| 4 | 3 | 4 |
|
|
114
|
+
| **Weighted Total** | **4.65** | **3.90** | **3.75** |
|
|
115
|
+
|
|
116
|
+
## Rationale
|
|
117
|
+
FastAPI's native async support eliminates thread pool overhead when calling
|
|
118
|
+
payment gateway APIs (avg 200ms latency). Auto-generated OpenAPI schema removes
|
|
119
|
+
manual documentation maintenance. Pydantic v2 validation is 5–10x faster than
|
|
120
|
+
DRF serializers for our data shapes.
|
|
121
|
+
|
|
122
|
+
## Rejected Alternatives
|
|
123
|
+
- **Django REST Framework**: Excellent for CRUD APIs with ORM but sync-by-default
|
|
124
|
+
adds unnecessary complexity for async-heavy workload. Migration to async views
|
|
125
|
+
is incomplete as of Django 4.2.
|
|
126
|
+
- **Flask**: Too minimal; would require adding marshmallow/apispec manually for
|
|
127
|
+
validation and docs. Higher integration maintenance cost.
|
|
128
|
+
|
|
129
|
+
## Consequences
|
|
130
|
+
- Team must learn FastAPI patterns (dependency injection, Pydantic models).
|
|
131
|
+
- Uvicorn + Gunicorn deployment is less familiar than Django's WSGI setup.
|
|
132
|
+
- Mitigation: 2-day internal workshop before sprint 1.
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### 6. Avoid These Anti-Patterns
|
|
136
|
+
|
|
137
|
+
- Choosing a technology because it's trending on HN/X — evaluate against actual requirements.
|
|
138
|
+
- Recommending a rewrite from a working stack without quantifying the migration cost and business risk.
|
|
139
|
+
- Picking microservices/distributed architecture for a team of < 5 engineers — operational overhead outweighs benefits.
|
|
140
|
+
- Choosing unproven (< 1 year old, < 1.0 release) libraries for production critical paths.
|
|
141
|
+
- Ignoring the existing team's expertise — a 20% performance gain is not worth a 6-month ramp-up.
|
|
142
|
+
|
|
143
|
+
## Edge Cases
|
|
144
|
+
|
|
145
|
+
**Post-decision monitoring:** After a technology is adopted, schedule a review at 6 months and 12 months. Review triggers: library goes unmaintained (no releases in 12 months, maintainer announces EOL), critical unpatched CVE, major version breaking change, or team dissatisfaction score drops below threshold. Document the review criteria in the ADR's Consequences section so the team knows when to revisit.
|
|
146
|
+
|
|
147
|
+
**Compliance hard-blocking disqualifiers:** Certain choices are non-negotiable regardless of rubric score. Examples: AGPL-licensed library in a proprietary SaaS product (distribution triggers copyleft), data residency requirements that rule out specific cloud regions, FIPS-140-2 requirement that rules out non-certified crypto libraries. Evaluate compliance blockers before scoring — a blocked option should not appear in the rubric at all.
|
|
148
|
+
|
|
149
|
+
**RFC/spike process for tie votes:** When the evaluation rubric produces a tie (within 0.3 points) and team discussion does not converge, run a time-boxed technical spike: one engineer builds a proof-of-concept with each finalist option for 2–3 days, then presents findings to the team. Vote after the spike. Document the spike outcome in the ADR. This prevents indefinite debate and grounds the decision in hands-on evidence.
|
|
150
|
+
|
|
151
|
+
**Greenfield vs. brownfield context**: For brownfield, always evaluate migration cost as a first-class criterion. A technically superior option that requires migrating 200k lines of code is often the wrong choice. Prefer "good enough and migratable" over "theoretically best but costly to adopt."
|
|
152
|
+
|
|
153
|
+
**Vendor lock-in analysis**: For managed services (Firebase, PlanetScale, Neon, Vercel), assess: What is the data export story? What is the cost at 10x current scale? Is there a self-hosted option if the vendor changes pricing? Document lock-in risk in the ADR's Consequences section.
|
|
154
|
+
|
|
155
|
+
**When options are genuinely equivalent**: If two options score within 0.3 of each other on the weighted rubric, choose based on: (1) team familiarity, (2) existing organizational investment (training, tooling, expertise). Document the tie-breaking rationale explicitly — do not leave it as "we chose X" without justification.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: taskorchestrator
|
|
3
|
+
description: Designs and implements asynchronous task queues, distributed workflows, and worker orchestration systems. Use when asked to build job queues, implement background workers, design saga workflows, handle retry logic, or configure dead-letter queues with Celery, BullMQ, or Temporal.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TaskOrchestrator
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Designs production-grade task orchestration systems using Celery (Python), BullMQ (Node.js), or Temporal (polyglot). Covers queue topology, worker concurrency, retry strategies with exponential backoff, dead-letter queues, idempotency, saga orchestration, and backpressure. Every design decision is justified against the specific failure mode it addresses.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Tool Selection
|
|
15
|
+
|
|
16
|
+
Choose the orchestration tool based on the workload profile:
|
|
17
|
+
|
|
18
|
+
| Tool | Language | Best For | Avoid When |
|
|
19
|
+
|------|----------|----------|------------|
|
|
20
|
+
| **Celery** | Python | High-throughput task queues, ML pipelines, Django/Flask integration | Long-running workflows with complex state; use Temporal instead |
|
|
21
|
+
| **BullMQ** | Node.js/TypeScript | Job queues with Redis backend, UI dashboard (Bull Board), rate limiting | Large Python teams; missing native workflow orchestration |
|
|
22
|
+
| **Temporal** | Python/Go/Java/TS | Long-running workflows, saga orchestration, durable execution with replay | Simple fire-and-forget tasks; adds operational overhead |
|
|
23
|
+
| **Celery + Kombu** | Python | When broker flexibility needed (RabbitMQ, SQS, Redis) | |
|
|
24
|
+
| **AWS SQS + Lambda** | Any | Serverless, event-driven, AWS-native; no infra to manage | Tasks > 15 min, complex orchestration logic |
|
|
25
|
+
| **Inngest / Trigger.dev** | TypeScript | Serverless-first Node.js workflows with built-in retries | Non-TypeScript stacks |
|
|
26
|
+
|
|
27
|
+
### 2. Queue Topology Design
|
|
28
|
+
|
|
29
|
+
Design queues before writing code:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
Priority queues: critical > high > default > low
|
|
33
|
+
- critical: payment processing, auth tokens
|
|
34
|
+
- high: user-triggered actions (export, import)
|
|
35
|
+
- default: background enrichment, notifications
|
|
36
|
+
- low: analytics, cleanup, maintenance tasks
|
|
37
|
+
|
|
38
|
+
Dead-letter queues: every queue has a corresponding DLQ
|
|
39
|
+
- orders.queue → orders.dlq
|
|
40
|
+
- emails.queue → emails.dlq
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Celery:** Use `task_routes` to map task name patterns to queue names. Set `x-max-priority: 10` on the critical queue.
|
|
44
|
+
|
|
45
|
+
**BullMQ:**
|
|
46
|
+
```typescript
|
|
47
|
+
const paymentQueue = new Queue('payments', {
|
|
48
|
+
connection: redis,
|
|
49
|
+
defaultJobOptions: { attempts: 5, backoff: { type: 'exponential', delay: 2000 },
|
|
50
|
+
removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 } }
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 3. Retry Strategy with Exponential Backoff
|
|
55
|
+
|
|
56
|
+
Use `retry_delay = min(base * 2^attempt + jitter, max_delay)`. Never fixed-interval retries.
|
|
57
|
+
|
|
58
|
+
**Celery:** `@celery_app.task(retry_backoff=True, retry_backoff_max=600, retry_jitter=True, max_retries=5)`. Raise `self.reject(requeue=False)` for permanent errors (invalid card, validation failure).
|
|
59
|
+
|
|
60
|
+
**Temporal:** Configure `RetryPolicy(initial_interval=2s, backoff_coefficient=2.0, maximum_attempts=5, non_retryable_error_types=["PermanentPaymentError"])` on `execute_activity`.
|
|
61
|
+
|
|
62
|
+
Distinguish retryable (network, 429, 5xx) from non-retryable (validation, 4xx, business rule violations).
|
|
63
|
+
|
|
64
|
+
### 4. Idempotency Keys
|
|
65
|
+
|
|
66
|
+
Every task that produces side effects must be idempotent:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# Pattern: idempotency key stored in DB with unique constraint
|
|
70
|
+
def send_email_idempotent(email_id: str, recipient: str, subject: str):
|
|
71
|
+
idempotency_key = f"email:{email_id}:{recipient}"
|
|
72
|
+
|
|
73
|
+
with db.transaction():
|
|
74
|
+
# Attempt insert; if it already exists, this email was already sent
|
|
75
|
+
try:
|
|
76
|
+
db.execute(
|
|
77
|
+
"INSERT INTO processed_tasks (idempotency_key, processed_at) VALUES (?, NOW())",
|
|
78
|
+
(idempotency_key,)
|
|
79
|
+
)
|
|
80
|
+
except UniqueConstraintError:
|
|
81
|
+
logger.info(f"Task already processed: {idempotency_key}")
|
|
82
|
+
return # idempotent no-op
|
|
83
|
+
|
|
84
|
+
# Only runs if insert succeeded (first time)
|
|
85
|
+
email_service.send(recipient, subject)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Use UUID v4 or content-based hash as idempotency key. Store in Redis with TTL for short-lived tasks, or in a DB table for audit trail requirements.
|
|
89
|
+
|
|
90
|
+
### 5. Dead-Letter Queue Handling
|
|
91
|
+
|
|
92
|
+
DLQs catch tasks that exhausted all retries. Never leave DLQs unmonitored:
|
|
93
|
+
1. **Alert**: when DLQ depth > threshold (e.g., > 10 messages in `payments.dlq`).
|
|
94
|
+
2. **Inspect**: Log task ID, queue, attempt count, last error, timestamp when routing to DLQ.
|
|
95
|
+
3. **Reprocess**: fix root cause first, then replay via `queue.retryJobs()` (BullMQ) or re-queue (Celery).
|
|
96
|
+
4. **Retention**: Keep DLQ messages 14 days minimum.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
# Celery dead-letter with RabbitMQ
|
|
100
|
+
Queue('default', queue_arguments={
|
|
101
|
+
'x-dead-letter-exchange': 'dlx',
|
|
102
|
+
'x-dead-letter-routing-key': 'default.dlq',
|
|
103
|
+
})
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 6. Backpressure
|
|
107
|
+
|
|
108
|
+
- **Celery**: `worker_prefetch_multiplier=1` prevents pre-fetching excess tasks. `task_acks_late=True` prevents loss on worker crash.
|
|
109
|
+
- **BullMQ**: Set `concurrency` and `limiter: { max: 100, duration: 60000 }` on the Worker.
|
|
110
|
+
- **Temporal**: `WorkerOptions.max_concurrent_activity_task_executions` limits parallelism. Use `workflow.pause()` if the downstream is unhealthy.
|
|
111
|
+
|
|
112
|
+
### 7. Monitoring and Observability
|
|
113
|
+
|
|
114
|
+
Key metrics per queue: task throughput (tasks/sec), queue depth (lag > 5 min = alert for high-priority), error rate (> 1% = alert on critical queues), worker saturation.
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
@task_failure.connect
|
|
118
|
+
def on_task_failure(task_id, exception, sender, **kwargs):
|
|
119
|
+
metrics.increment('celery.task.failure', tags=[f'task:{sender.name}'])
|
|
120
|
+
logger.error("Task failed", extra={"task_id": task_id, "error": str(exception)})
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Use **Flower** (Celery) or **Bull Board** (BullMQ) for dashboards. Temporal Cloud provides built-in workflow visibility.
|
|
124
|
+
|
|
125
|
+
## Additional Patterns
|
|
126
|
+
|
|
127
|
+
**Temporal determinism requirement:** Temporal workflows are replayed from event history to resume after crashes. This means workflow code must be fully deterministic: never call `datetime.now()`, `random.random()`, `uuid4()`, or any I/O (DB, HTTP, filesystem) directly in the workflow body. All non-deterministic operations must be placed in activities. Use `workflow.now()` for current time and `workflow.uuid4()` for IDs inside workflows.
|
|
128
|
+
|
|
129
|
+
## Edge Cases
|
|
130
|
+
|
|
131
|
+
**Long-running tasks and worker restarts**: For tasks that run > 5 minutes, use Temporal's durable execution (workflows survive worker restarts via event sourcing replay) or implement a heartbeat mechanism in Celery (`self.update_state(state='PROGRESS')` + monitor for stale heartbeats). Never run long tasks in a queue designed for fast tasks — separate pools.
|
|
132
|
+
|
|
133
|
+
**Task deduplication**: Prevent the same logical task from being enqueued twice (e.g., double-click on "Export" button). Implement deduplication at enqueue time: check for an in-progress job with the same key before adding to the queue. BullMQ supports `jobId` deduplication natively. For Celery, use Redis `SET NX` with TTL as a distributed lock before calling `.apply_async()`.
|
|
134
|
+
|
|
135
|
+
**Poison pill messages**: A malformed message that always causes a task to crash will cycle through retries and fill the DLQ. Detect by inspecting DLQ for repeated task signatures. Add a payload validation step at the start of every task handler that raises a non-retryable exception on schema validation failure — this routes malformed messages to DLQ immediately without wasting retry attempts.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: testcrafter
|
|
3
|
+
description: Writes unit and integration tests using Jest, Vitest, Pytest, or JUnit following the AAA pattern and test pyramid principles. Use when asked to write tests, improve test coverage, set up a testing strategy, configure CI test gates, or decide between mocking vs. real implementations.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TestCrafter
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Produces high-quality, maintainable tests following the AAA (Arrange-Act-Assert) pattern, test pyramid principles, and clear naming conventions. Framework-specific guidance for Jest/Vitest (JavaScript/TypeScript), Pytest (Python), and JUnit 5 (Java). Targets 80% line coverage as a floor, with emphasis on testing behavior over implementation.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Test Pyramid Strategy
|
|
15
|
+
|
|
16
|
+
Before writing tests, identify the appropriate layer:
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
/\
|
|
20
|
+
/E2E\ ~5% — Playwright/Cypress/Selenium; slow, costly, high confidence
|
|
21
|
+
/------\
|
|
22
|
+
/Integr. \ ~20% — DB, HTTP, message queue integration; real dependencies
|
|
23
|
+
/----------\
|
|
24
|
+
/ Unit Tests \ ~75% — Pure logic, isolated, fast (< 10ms each)
|
|
25
|
+
/--------------\
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**Unit tests**: Test one function/class in isolation. Mock all external dependencies (DB, HTTP, filesystem, time). Goal: < 10ms per test, no I/O.
|
|
29
|
+
|
|
30
|
+
**Integration tests**: Test the interaction between components (e.g., repository + real DB, HTTP handler + real router). Use test containers (Testcontainers library) or an in-memory DB (SQLite for PostgreSQL compatibility testing, `mongomock` for MongoDB).
|
|
31
|
+
|
|
32
|
+
**E2E tests**: Test the full user journey through the real UI. Reserve for critical paths only (login, checkout, core workflow). Do not write E2E tests for every feature.
|
|
33
|
+
|
|
34
|
+
### 2. Naming Convention
|
|
35
|
+
|
|
36
|
+
Use the **"should [expected behavior] when [condition]"** pattern:
|
|
37
|
+
|
|
38
|
+
```javascript
|
|
39
|
+
// Good
|
|
40
|
+
describe('UserService', () => {
|
|
41
|
+
describe('createUser', () => {
|
|
42
|
+
it('should return the created user with an assigned ID when valid data is provided')
|
|
43
|
+
it('should throw ValidationError when email is already taken')
|
|
44
|
+
it('should hash the password before persisting to the database')
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
# Pytest: use descriptive function names
|
|
51
|
+
def test_create_user_returns_user_with_id_when_valid_data():
|
|
52
|
+
def test_create_user_raises_validation_error_when_email_taken():
|
|
53
|
+
def test_create_user_hashes_password_before_persisting():
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Avoid: `test1`, `testHappyPath`, `test_create_user_works`. The test name should be self-documenting enough to diagnose a failure without reading the test body.
|
|
57
|
+
|
|
58
|
+
### 3. AAA Pattern Implementation
|
|
59
|
+
|
|
60
|
+
Every test has exactly three sections: Arrange, Act, Assert.
|
|
61
|
+
|
|
62
|
+
**Jest/Vitest (TypeScript)** — mock the repo, call the service, assert the result:
|
|
63
|
+
```typescript
|
|
64
|
+
it('should return created user with ID when valid data is provided', async () => {
|
|
65
|
+
// Arrange
|
|
66
|
+
mockUserRepo.findByEmail.mockResolvedValue(null);
|
|
67
|
+
mockUserRepo.save.mockResolvedValue({ id: 'uuid-123', email: 'user@example.com' });
|
|
68
|
+
// Act
|
|
69
|
+
const result = await userService.createUser({ email: 'user@example.com', password: 'secret' });
|
|
70
|
+
// Assert
|
|
71
|
+
expect(result.id).toBe('uuid-123');
|
|
72
|
+
expect(mockUserRepo.save).toHaveBeenCalledOnce();
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**Pytest**:
|
|
77
|
+
```python
|
|
78
|
+
def test_returns_user_with_id_when_valid_data(self):
|
|
79
|
+
self.mock_repo.find_by_email.return_value = None
|
|
80
|
+
self.mock_repo.save.return_value = {"id": "uuid-123", "email": "u@example.com"}
|
|
81
|
+
result = self.service.create_user(email="u@example.com", password="secret")
|
|
82
|
+
assert result["id"] == "uuid-123"
|
|
83
|
+
self.mock_repo.save.assert_called_once()
|
|
84
|
+
|
|
85
|
+
def test_raises_validation_error_when_email_taken(self):
|
|
86
|
+
self.mock_repo.find_by_email.return_value = {"id": "existing"}
|
|
87
|
+
with pytest.raises(ValidationError, match="Email already in use"):
|
|
88
|
+
self.service.create_user(email="u@example.com", password="secret")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 4. Mock vs. Real Dependencies
|
|
92
|
+
|
|
93
|
+
**Mock** when the dependency has slow I/O, non-deterministic behavior, or you need to force specific error paths. Always mock in unit tests.
|
|
94
|
+
|
|
95
|
+
**Use real implementations** when testing the integration itself (repository + DB). Use Testcontainers (`PostgreSqlContainer`, `@testcontainers/postgresql`) for integration tests — spin up a real DB in `beforeAll`, run migrations, then tear down in `afterAll`.
|
|
96
|
+
|
|
97
|
+
**Avoid partial mocks** — they couple tests to implementation and hide bugs.
|
|
98
|
+
|
|
99
|
+
### 5. Framework-Specific Configuration
|
|
100
|
+
|
|
101
|
+
**Vitest** (`vitest.config.ts`):
|
|
102
|
+
```typescript
|
|
103
|
+
export default defineConfig({
|
|
104
|
+
test: {
|
|
105
|
+
globals: true, environment: 'node',
|
|
106
|
+
coverage: {
|
|
107
|
+
provider: 'v8', reporter: ['text', 'lcov'],
|
|
108
|
+
thresholds: { lines: 80, functions: 80, branches: 75 },
|
|
109
|
+
exclude: ['**/*.config.*', '**/migrations/**'],
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Pytest** (`pyproject.toml`):
|
|
116
|
+
```toml
|
|
117
|
+
[tool.pytest.ini_options]
|
|
118
|
+
addopts = "--cov=app --cov-report=term-missing --cov-fail-under=80"
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**JUnit 5**: configure Jacoco with `<minimum>0.80</minimum>` on `LINE` counter.
|
|
122
|
+
|
|
123
|
+
### 6. Coverage Strategy
|
|
124
|
+
|
|
125
|
+
80% line coverage is a floor. Priorities: (1) 100% on domain logic and calculation functions; (2) every `catch` block and error path; (3) boundary conditions (empty, null, min/max). Exclude `toString()`, getters/setters, and generated code. Use `vitest --coverage` for branch coverage; `--cov-report=term-missing` in Pytest.
|
|
126
|
+
|
|
127
|
+
### 7. CI Integration
|
|
128
|
+
|
|
129
|
+
```yaml
|
|
130
|
+
- name: Run tests with coverage
|
|
131
|
+
run: npx vitest run --coverage
|
|
132
|
+
- name: Upload coverage
|
|
133
|
+
uses: codecov/codecov-action@v4
|
|
134
|
+
with: { token: "${{ secrets.CODECOV_TOKEN }}", fail_ci_if_error: true }
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Block PRs on test failures and coverage drops > 2% from main baseline.
|
|
138
|
+
|
|
139
|
+
## Additional Patterns
|
|
140
|
+
|
|
141
|
+
**WebSocket testing:** Mock the `WebSocket` constructor in unit tests to avoid real connections:
|
|
142
|
+
```typescript
|
|
143
|
+
const mockWs = { send: vi.fn(), close: vi.fn(), onmessage: null, onopen: null };
|
|
144
|
+
vi.stubGlobal('WebSocket', vi.fn(() => mockWs));
|
|
145
|
+
// Simulate incoming message
|
|
146
|
+
mockWs.onmessage?.({ data: JSON.stringify({ type: 'update', payload: 42 }) });
|
|
147
|
+
```
|
|
148
|
+
For integration tests, use a real `ws` server spun up in `beforeAll` on a random port.
|
|
149
|
+
|
|
150
|
+
**Large parameterized test performance:** When `pytest.mark.parametrize` produces thousands of cases (e.g., fuzzing inputs), test runs can take minutes. Apply stratified sampling: group inputs by equivalence class and pick one representative per class. For CI speed, split the full suite across workers with `pytest-xdist` (`pytest -n auto`), and run the full set only on main branch merges.
|
|
151
|
+
|
|
152
|
+
## Edge Cases
|
|
153
|
+
|
|
154
|
+
**Testing async code and timers**: Use `vi.useFakeTimers()` (Vitest) or `pytest-asyncio` + `asyncio.sleep` mocking to control time in tests. Never use `setTimeout(fn, 0)` or `asyncio.sleep(0.1)` in tests — they create flaky tests dependent on real time. Use `vi.advanceTimersByTime(5000)` to simulate time passage deterministically.
|
|
155
|
+
|
|
156
|
+
**Testing code with global state / singletons**: Reset global state in `beforeEach`/`afterEach`. For module-level singletons in Node.js, use `vi.resetModules()` to get a fresh module instance per test. For Python, use `importlib.reload()` or redesign the singleton to accept injected dependencies (constructor injection is inherently more testable).
|
|
157
|
+
|
|
158
|
+
**Snapshot tests**: Use Jest/Vitest snapshot tests sparingly — only for stable serialized output (serialized ASTs, rendered static HTML). Never snapshot for UI components that change frequently; use explicit assertions instead. Stale snapshots silently pass until someone runs `--updateSnapshot`, masking regressions. If a snapshot test fails unexpectedly, treat it as a regression, not an automatic update.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: tracemind
|
|
3
|
+
description: Implements distributed tracing, structured logging, and observability using OpenTelemetry, Jaeger/Tempo, and SLO-based alerting. Use when asked to add tracing to a service, implement structured logging, set up correlation IDs, configure OpenTelemetry, analyze stack traces, or build SLO alerts.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TraceMind
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Implements the three pillars of observability — traces, metrics, and logs — using OpenTelemetry as the vendor-neutral instrumentation layer. Backends: Jaeger or Grafana Tempo for traces, Prometheus + Grafana for metrics, and any JSON-structured log aggregator (Loki, Datadog, Elasticsearch). Produces correlation IDs that stitch traces, logs, and metrics together for root-cause analysis.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. OpenTelemetry Setup
|
|
15
|
+
|
|
16
|
+
OpenTelemetry is the instrumentation standard. Instrument once, export to any backend.
|
|
17
|
+
|
|
18
|
+
**Python (FastAPI)**:
|
|
19
|
+
```python
|
|
20
|
+
from opentelemetry import trace
|
|
21
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
22
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
23
|
+
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
|
24
|
+
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
|
25
|
+
|
|
26
|
+
def setup_tracing(service_name: str, otlp_endpoint: str):
|
|
27
|
+
provider = TracerProvider(resource=Resource.create({SERVICE_NAME: service_name}))
|
|
28
|
+
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=otlp_endpoint)))
|
|
29
|
+
trace.set_tracer_provider(provider)
|
|
30
|
+
FastAPIInstrumentor.instrument()
|
|
31
|
+
HTTPXClientInstrumentor.instrument()
|
|
32
|
+
SQLAlchemyInstrumentor.instrument()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Node.js**: Load `tracing.ts` before all other imports. Use `NodeSDK` with `getNodeAutoInstrumentations()` and `OTLPTraceExporter`. Configure via `OTEL_EXPORTER_OTLP_ENDPOINT` env var.
|
|
36
|
+
|
|
37
|
+
### 2. Trace Context Propagation
|
|
38
|
+
|
|
39
|
+
Traces must flow across service boundaries using W3C Trace Context (`traceparent` header):
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
traceparent: 00-{trace-id-32hex}-{parent-span-id-16hex}-{flags}
|
|
43
|
+
tracestate: vendor-specific key-value pairs
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Auto-instrumentation handles this for HTTP clients (httpx, axios, requests). For message queues, inject manually:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
# Inject trace context into Kafka message headers
|
|
50
|
+
from opentelemetry.propagate import inject
|
|
51
|
+
|
|
52
|
+
headers = {}
|
|
53
|
+
inject(headers) # adds 'traceparent' and 'tracestate'
|
|
54
|
+
producer.send('orders', value=payload, headers=list(headers.items()))
|
|
55
|
+
|
|
56
|
+
# Extract in consumer
|
|
57
|
+
from opentelemetry.propagate import extract
|
|
58
|
+
from opentelemetry import trace
|
|
59
|
+
|
|
60
|
+
ctx = extract(dict(message.headers))
|
|
61
|
+
with trace.get_tracer(__name__).start_as_current_span(
|
|
62
|
+
"process-order", context=ctx
|
|
63
|
+
) as span:
|
|
64
|
+
...
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
For async/background workers (Celery, BullMQ): serialize the trace context as a task header and restore it in the worker.
|
|
68
|
+
|
|
69
|
+
### 3. Structured Logging with Correlation IDs
|
|
70
|
+
|
|
71
|
+
All logs must be JSON-structured with trace context embedded. Use a structlog processor to inject `trace_id` and `span_id` from the active OTel span into every log entry. Required fields: `event`, `timestamp` (ISO 8601), `service`, `env`, `trace_id`, `span_id`.
|
|
72
|
+
|
|
73
|
+
**Never log**: passwords, API keys, PII (emails, SSNs) in plaintext. Redact with `***` or hash.
|
|
74
|
+
|
|
75
|
+
### 4. Custom Spans and Attributes
|
|
76
|
+
|
|
77
|
+
Name spans `<domain>.<operation>` (`payment.process`, `db.query`, `cache.get`). Set domain attributes on the span, call `span.record_exception(e)` and `span.set_status(StatusCode.ERROR)` in the except block. Follow OTel Semantic Conventions (`db.system`, `http.method`) for standard attributes; use `<service>.<attribute>` for domain-specific ones.
|
|
78
|
+
|
|
79
|
+
### 5. SLO Definition and Alerting
|
|
80
|
+
|
|
81
|
+
Define SLOs before configuring alerts. SLI = HTTP 2xx / total requests. SLO = 99.9% over 30-day window. Error budget = 43.8 min/month.
|
|
82
|
+
|
|
83
|
+
Key Prometheus alert expressions:
|
|
84
|
+
- Error rate: `sum(rate(http_requests_total{status!~"5.."}[5m])) / sum(rate(http_requests_total[5m])) < 0.999`
|
|
85
|
+
- Latency p99: `histogram_quantile(0.99, ...) > 1.0`
|
|
86
|
+
|
|
87
|
+
**Error budget burn rate** (Google SRE Workbook): fast burn (1h, 14x) = page; slow burn (6h, 6x) = ticket; very slow (3d, 3x) = sprint review.
|
|
88
|
+
|
|
89
|
+
### 6. Grafana Dashboard Structure
|
|
90
|
+
|
|
91
|
+
Use the RED method: Request rate, Error rate, Duration (p50/p95/p99). Include an error budget remaining panel (green > 50%, yellow 10–50%, red < 10%). Link panels directly to Tempo/Jaeger trace queries for the selected time range.
|
|
92
|
+
|
|
93
|
+
### 7. OTel Collector Configuration
|
|
94
|
+
|
|
95
|
+
Route telemetry through an OTel Collector (not directly to backends) for flexibility:
|
|
96
|
+
|
|
97
|
+
```yaml
|
|
98
|
+
# otel-collector-config.yaml
|
|
99
|
+
receivers:
|
|
100
|
+
otlp:
|
|
101
|
+
protocols:
|
|
102
|
+
grpc: { endpoint: "0.0.0.0:4317" }
|
|
103
|
+
http: { endpoint: "0.0.0.0:4318" }
|
|
104
|
+
|
|
105
|
+
processors:
|
|
106
|
+
batch:
|
|
107
|
+
timeout: 5s
|
|
108
|
+
send_batch_size: 1000
|
|
109
|
+
resource:
|
|
110
|
+
attributes:
|
|
111
|
+
- action: insert
|
|
112
|
+
key: deployment.environment
|
|
113
|
+
value: ${ENV}
|
|
114
|
+
|
|
115
|
+
exporters:
|
|
116
|
+
otlp/tempo:
|
|
117
|
+
endpoint: "tempo:4317"
|
|
118
|
+
tls: { insecure: true }
|
|
119
|
+
prometheus:
|
|
120
|
+
endpoint: "0.0.0.0:8889"
|
|
121
|
+
loki:
|
|
122
|
+
endpoint: "http://loki:3100/loki/api/v1/push"
|
|
123
|
+
|
|
124
|
+
service:
|
|
125
|
+
pipelines:
|
|
126
|
+
traces: { receivers: [otlp], processors: [batch], exporters: [otlp/tempo] }
|
|
127
|
+
metrics: { receivers: [otlp], processors: [batch], exporters: [prometheus] }
|
|
128
|
+
logs: { receivers: [otlp], processors: [batch], exporters: [loki] }
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Edge Cases
|
|
132
|
+
|
|
133
|
+
**Sampling strategy:** At > 1000 req/s, use tail-based sampling: always record traces with errors or high latency, sample 1–5% of healthy fast traces. Configure via OTel Collector `tailsampling` processor. Never use head-based sampling alone.
|
|
134
|
+
|
|
135
|
+
**Trace context across async boundaries:** `asyncio.gather()`, `ThreadPoolExecutor`, and message queues do not auto-propagate context. Use `contextvars.copy_context()` when spawning threads. For message queues, inject/extract manually (see Section 2).
|
|
136
|
+
|
|
137
|
+
**Cardinality explosion:** High-cardinality labels (user IDs, full URL paths) cause Prometheus memory exhaustion. Use `http.route` (pattern) not `http.url` (full URL). Audit with `promtool tsdb analyze`.
|
|
138
|
+
|
|
139
|
+
**Clock skew diagnosis:** Spans with impossible durations (negative or longer than the parent) indicate NTP drift or container clock skew. Check `chronyc tracking` on host nodes and verify container time sync. In Kubernetes, pods inherit host clock — a skewed node affects all pods. Use Jaeger's clock skew adjustment or correct the node NTP source.
|
|
140
|
+
|
|
141
|
+
**OTel Collector HA:** Run the Collector as a DaemonSet or sidecar for local buffering. Configure the `batch` processor with `sending_queue` and `retry_on_failure` to buffer spans during backend outages. Add a fallback exporter (e.g., write to file) so telemetry is not lost if the primary backend is down.
|
|
142
|
+
|
|
143
|
+
**PII in span attributes:** Avoid setting user emails, names, or payment data as span attributes — they appear in trace UIs and logs. If unavoidable, use the OTel Collector `transform` processor to redact or hash sensitive attributes before export: `set(attributes["user.email"], "REDACTED") where attributes["user.email"] != nil`.
|