everything-gemini 1.8.0 → 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/CHANGELOG.md +47 -0
- package/CONTRIBUTING.md +5 -0
- package/README.md +28 -9
- package/agents/mlops-engineer.md +33 -0
- package/agents/platform-engineer.md +33 -0
- package/bin/everything-gemini +390 -18
- package/docs/LAUNCH_KIT_v2.0.0.md +187 -0
- package/docs/architecture/progressive-disclosure.md +3 -3
- package/docs/index.html +23 -7
- package/examples/python-sdk/README.md +8 -0
- package/examples/python-sdk/autonomous_mlops_rag_pipeline.py +254 -0
- package/examples/python-sdk/platform_provisioning_pipeline.py +193 -0
- package/mcp/README.md +2 -0
- package/mcp/mcp_config.example.json +11 -0
- package/package.json +1 -1
- package/scripts/validate.sh +1 -1
- package/skills/chromadb-vector-store/SKILL.md +188 -0
- package/skills/cloudflare-r2-object-storage/SKILL.md +143 -0
- package/skills/distributed-rate-limiting/SKILL.md +138 -0
- package/skills/keda-event-autoscaling/SKILL.md +218 -0
- package/skills/milvus-vector-clustering/SKILL.md +134 -0
- package/skills/opa-gatekeeper-policy/SKILL.md +200 -0
- package/skills/triton-inference-server/SKILL.md +221 -0
- package/skills/vault-secrets-management/SKILL.md +129 -0
- package/templates/full-power/mcp_config.json +11 -0
- package/tests/cli.test.js +118 -11
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: distributed-rate-limiting
|
|
3
|
+
description: >-
|
|
4
|
+
Architects, implements, and tunes distributed rate limiting using Redis sliding window logs, token buckets, tiered API quotas, RFC 6585 headers, and circuit breakers.
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Distributed Rate Limiting & API Traffic Shaping
|
|
8
|
+
|
|
9
|
+
This skill guides the design, implementation, and tuning of distributed rate limiting systems across microservice clusters using Redis, token buckets, and sliding window algorithms.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## ⚡ Algorithm Comparison Matrix
|
|
14
|
+
|
|
15
|
+
| Algorithm | Precision | Memory Usage | Burst Handling | Best For |
|
|
16
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
17
|
+
| **`Sliding Window Log`** | 100% Exact | High ($O(N)$ requests) | Excellent | Low-to-medium traffic sensitive endpoints (auth, payments). |
|
|
18
|
+
| **`Sliding Window Counter`**| ~99% Exact | Fixed ($O(1)$) | Smooth | High-scale public APIs and ingress gateways. |
|
|
19
|
+
| **`Token Bucket`** | High | Very Low ($O(1)$) | Controlled bursts | Standard microservice backpressuring and rate smoothing. |
|
|
20
|
+
| **`Fixed Window`** | Poor (2x burst at boundary) | Lowest | Prone to spikes | Simple non-critical background jobs only. |
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 🔒 Atomic Sliding Window Rate Limiter (Redis Lua)
|
|
25
|
+
|
|
26
|
+
Atomic execution in Redis ensures no race conditions across distributed API instances:
|
|
27
|
+
|
|
28
|
+
```lua
|
|
29
|
+
-- sliding_window.lua
|
|
30
|
+
-- KEYS[1]: Rate limit key (e.g., "ratelimit:tenant_123:orders")
|
|
31
|
+
-- ARGV[1]: Current UNIX timestamp in milliseconds
|
|
32
|
+
-- ARGV[2]: Window size in milliseconds (e.g., 60000 for 1 minute)
|
|
33
|
+
-- ARGV[3]: Maximum allowed requests in window (e.g., 100)
|
|
34
|
+
|
|
35
|
+
local key = KEYS[1]
|
|
36
|
+
local now = tonumber(ARGV[1])
|
|
37
|
+
local window = tonumber(ARGV[2])
|
|
38
|
+
local limit = tonumber(ARGV[3])
|
|
39
|
+
local clearBefore = now - window
|
|
40
|
+
|
|
41
|
+
-- 1. Remove expired request timestamps outside the window
|
|
42
|
+
redis.call('ZREMRANGEBYSCORE', key, 0, clearBefore)
|
|
43
|
+
|
|
44
|
+
-- 2. Count requests currently in the sliding window
|
|
45
|
+
local currentRequests = redis.call('ZCARD', key)
|
|
46
|
+
|
|
47
|
+
if currentRequests < limit then
|
|
48
|
+
-- 3. Register current request with unique timestamp as score and member
|
|
49
|
+
redis.call('ZADD', key, now, now .. '-' .. math.random(1000, 9999))
|
|
50
|
+
redis.call('PEXPIRE', key, window)
|
|
51
|
+
return { 1, limit - currentRequests - 1, 0 } -- [Allowed: 1, Remaining, RetryAfter: 0]
|
|
52
|
+
else
|
|
53
|
+
-- 4. Calculate time until oldest entry expires
|
|
54
|
+
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
|
|
55
|
+
local retryAfter = math.ceil((tonumber(oldest[2]) + window - now) / 1000)
|
|
56
|
+
return { 0, 0, math.max(1, retryAfter) } -- [Allowed: 0, Remaining: 0, RetryAfter]
|
|
57
|
+
end
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 🌐 Express / Fastify / Node.js Middleware Implementation
|
|
63
|
+
|
|
64
|
+
Wrap Redis Lua execution into production middleware with RFC 6585 compliance:
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
import { Request, Response, NextFunction } from 'express';
|
|
68
|
+
import Redis from 'ioredis';
|
|
69
|
+
|
|
70
|
+
const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
|
|
71
|
+
|
|
72
|
+
export function createRateLimiter(options: { windowMs: number; max: number; keyGenerator?: (req: Request) => string }) {
|
|
73
|
+
return async (req: Request, res: Response, next: NextFunction) => {
|
|
74
|
+
const key = options.keyGenerator ? options.keyGenerator(req) : `ratelimit:${req.ip}`;
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
const [allowed, remaining, retryAfter] = await redis.eval(
|
|
79
|
+
SLIDING_WINDOW_LUA_SCRIPT,
|
|
80
|
+
1,
|
|
81
|
+
key,
|
|
82
|
+
now.toString(),
|
|
83
|
+
options.windowMs.toString(),
|
|
84
|
+
options.max.toString()
|
|
85
|
+
) as [number, number, number];
|
|
86
|
+
|
|
87
|
+
// Set standard RFC 6585 RateLimit response headers
|
|
88
|
+
res.setHeader('X-RateLimit-Limit', options.max);
|
|
89
|
+
res.setHeader('X-RateLimit-Remaining', remaining);
|
|
90
|
+
res.setHeader('X-RateLimit-Reset', Math.ceil((now + options.windowMs) / 1000));
|
|
91
|
+
|
|
92
|
+
if (allowed === 1) {
|
|
93
|
+
return next();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
res.setHeader('Retry-After', retryAfter);
|
|
97
|
+
return res.status(429).json({
|
|
98
|
+
error: 'Too Many Requests',
|
|
99
|
+
message: `Rate limit exceeded. Please retry after ${retryAfter} seconds.`,
|
|
100
|
+
retryAfter,
|
|
101
|
+
});
|
|
102
|
+
} catch (err) {
|
|
103
|
+
// Circuit Breaker: Fail-Open for high availability if Redis degrades
|
|
104
|
+
console.error('RateLimiter Redis failure, failing open:', err);
|
|
105
|
+
return next();
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## 🎯 Tiered Multi-Dimensional Quotas
|
|
114
|
+
|
|
115
|
+
Configure tiered rate limits based on authenticated API keys and endpoint criticality:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
export function getTierLimits(tier: 'free' | 'pro' | 'enterprise') {
|
|
119
|
+
switch (tier) {
|
|
120
|
+
case 'enterprise':
|
|
121
|
+
return { windowMs: 60_000, max: 10_000 };
|
|
122
|
+
case 'pro':
|
|
123
|
+
return { windowMs: 60_000, max: 1_200 };
|
|
124
|
+
case 'free':
|
|
125
|
+
default:
|
|
126
|
+
return { windowMs: 60_000, max: 60 };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 📋 Architectural Rules & Best Practices
|
|
134
|
+
|
|
135
|
+
1. **Atomic Scripts**: Never implement rate limiters with separated `GET` and `INCR` commands; always execute atomic Lua scripts or Redis Transactions (`MULTI/EXEC`) to prevent race conditions under load.
|
|
136
|
+
2. **Fail-Open Strategy**: For user-facing critical flows, catch Redis connection timeouts and fail-open with alerting rather than causing total service outages.
|
|
137
|
+
3. **Multi-Dimensional Keys**: Combine client identity with endpoint routes (e.g. `tenant:123:POST:/api/v1/checkout`) to prevent denial of service on high-cost endpoints.
|
|
138
|
+
4. **Header Standards**: Always emit `Retry-After`, `X-RateLimit-Limit`, and `X-RateLimit-Remaining` to allow compliant clients to back off exponentially.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: keda-event-autoscaling
|
|
3
|
+
description: Architects and configures Kubernetes Event-driven Autoscaling (KEDA) ScaledObjects, ScaledJobs, and event triggers for automated scale-to-zero and burst workloads.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# KEDA Event-Driven Autoscaling
|
|
7
|
+
|
|
8
|
+
Configures Kubernetes Event-driven Autoscaling (KEDA) to dynamically scale workloads from 0 to N replicas based on external event queues, metrics streams, and consumer lag.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Core Architecture
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
External Event Source KEDA Operator Kubernetes Runtime
|
|
16
|
+
┌──────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐
|
|
17
|
+
│ Kafka / Redis / SQS │────>│ keda-metrics-apiserver ──────>│ HorizontalPodAutoscaler │
|
|
18
|
+
│ Prometheus / PubSub │ │ (Metrics Provider)│ │ (Target Replicas) │
|
|
19
|
+
└──────────────────────┘ └─────────┬─────────┘ └──────────┬───────────┘
|
|
20
|
+
│ │
|
|
21
|
+
┌─────────▼─────────┐ ┌──────────▼───────────┐
|
|
22
|
+
│ ScaledObject CRD │────>│ Scaled Deployment │
|
|
23
|
+
│ (0 <-> 1 Replica) │ │ (Min: 0, Max: 50) │
|
|
24
|
+
└───────────────────┘ └──────────────────────┘
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- **Metrics Server**: Translates external trigger metrics into standard Kubernetes custom metrics for the native HPA.
|
|
28
|
+
- **Scale to Zero (0 -> 1)**: Handled directly by KEDA controller activating idle deployments when events arrive.
|
|
29
|
+
- **Scale Beyond One (1 -> N)**: Handled by native Kubernetes HPA driven by KEDA external metrics.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 2. Kafka Consumer Lag ScaledObject
|
|
34
|
+
|
|
35
|
+
Scales pod replicas based on consumer group topic lag with secure secret authentication:
|
|
36
|
+
|
|
37
|
+
```yaml
|
|
38
|
+
apiVersion: keda.sh/v1alpha1
|
|
39
|
+
kind: TriggerAuthentication
|
|
40
|
+
metadata:
|
|
41
|
+
name: kafka-trigger-auth
|
|
42
|
+
namespace: production
|
|
43
|
+
spec:
|
|
44
|
+
secretTargetRef:
|
|
45
|
+
- parameter: sasl
|
|
46
|
+
name: kafka-credentials
|
|
47
|
+
key: sasl-mechanism
|
|
48
|
+
- parameter: username
|
|
49
|
+
name: kafka-credentials
|
|
50
|
+
key: sasl-username
|
|
51
|
+
- parameter: password
|
|
52
|
+
name: kafka-credentials
|
|
53
|
+
key: sasl-password
|
|
54
|
+
---
|
|
55
|
+
apiVersion: keda.sh/v1alpha1
|
|
56
|
+
kind: ScaledObject
|
|
57
|
+
metadata:
|
|
58
|
+
name: order-processor-scaler
|
|
59
|
+
namespace: production
|
|
60
|
+
spec:
|
|
61
|
+
scaleTargetRef:
|
|
62
|
+
apiVersion: apps/v1
|
|
63
|
+
kind: Deployment
|
|
64
|
+
name: order-processor
|
|
65
|
+
pollingInterval: 15
|
|
66
|
+
cooldownPeriod: 120
|
|
67
|
+
idleReplicaCount: 0
|
|
68
|
+
minReplicaCount: 1
|
|
69
|
+
maxReplicaCount: 40
|
|
70
|
+
advanced:
|
|
71
|
+
horizontalPodAutoscalerConfig:
|
|
72
|
+
behavior:
|
|
73
|
+
scaleDown:
|
|
74
|
+
stabilizationWindowSeconds: 300
|
|
75
|
+
policies:
|
|
76
|
+
- type: Percent
|
|
77
|
+
value: 20
|
|
78
|
+
periodSeconds: 60
|
|
79
|
+
scaleUp:
|
|
80
|
+
stabilizationWindowSeconds: 0
|
|
81
|
+
policies:
|
|
82
|
+
- type: Percent
|
|
83
|
+
value: 100
|
|
84
|
+
periodSeconds: 15
|
|
85
|
+
triggers:
|
|
86
|
+
- type: kafka
|
|
87
|
+
metadata:
|
|
88
|
+
bootstrapServers: kafka-cluster-kafka-bootstrap.kafka.svc.cluster.local:9092
|
|
89
|
+
consumerGroup: order-processor-group
|
|
90
|
+
topic: orders.v1
|
|
91
|
+
lagThreshold: "100"
|
|
92
|
+
activationLagThreshold: "1"
|
|
93
|
+
authenticationRef:
|
|
94
|
+
name: kafka-trigger-auth
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## 3. Redis Queue & Stream ScaledObject
|
|
100
|
+
|
|
101
|
+
Scales Celery or BullMQ worker queues dynamically based on pending queue length:
|
|
102
|
+
|
|
103
|
+
```yaml
|
|
104
|
+
apiVersion: keda.sh/v1alpha1
|
|
105
|
+
kind: ScaledObject
|
|
106
|
+
metadata:
|
|
107
|
+
name: celery-worker-scaler
|
|
108
|
+
namespace: production
|
|
109
|
+
spec:
|
|
110
|
+
scaleTargetRef:
|
|
111
|
+
name: celery-worker
|
|
112
|
+
minReplicaCount: 0
|
|
113
|
+
maxReplicaCount: 20
|
|
114
|
+
pollingInterval: 10
|
|
115
|
+
cooldownPeriod: 60
|
|
116
|
+
triggers:
|
|
117
|
+
- type: redis
|
|
118
|
+
metadata:
|
|
119
|
+
address: redis-cluster.cache.svc.cluster.local:6379
|
|
120
|
+
listName: celery
|
|
121
|
+
listLength: "50"
|
|
122
|
+
activationListLength: "1"
|
|
123
|
+
enableTLS: "true"
|
|
124
|
+
authenticationRef:
|
|
125
|
+
name: redis-trigger-auth
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## 4. ScaledJob for Finite Batch Workloads
|
|
131
|
+
|
|
132
|
+
Spawns isolated Kubernetes Jobs for batch or run-to-completion work (1 job per event):
|
|
133
|
+
|
|
134
|
+
```yaml
|
|
135
|
+
apiVersion: keda.sh/v1alpha1
|
|
136
|
+
kind: ScaledJob
|
|
137
|
+
metadata:
|
|
138
|
+
name: heavy-video-transcoder
|
|
139
|
+
namespace: batch
|
|
140
|
+
spec:
|
|
141
|
+
jobTargetRef:
|
|
142
|
+
parallelism: 1
|
|
143
|
+
completions: 1
|
|
144
|
+
activeDeadlineSeconds: 1800
|
|
145
|
+
backoffLimit: 2
|
|
146
|
+
template:
|
|
147
|
+
spec:
|
|
148
|
+
restartPolicy: OnFailure
|
|
149
|
+
containers:
|
|
150
|
+
- name: transcoder
|
|
151
|
+
image: registry.example.com/video-transcoder:v2.0.0
|
|
152
|
+
resources:
|
|
153
|
+
requests:
|
|
154
|
+
cpu: "2"
|
|
155
|
+
memory: 4Gi
|
|
156
|
+
pollingInterval: 30
|
|
157
|
+
successfulJobsHistoryLimit: 5
|
|
158
|
+
failedJobsHistoryLimit: 10
|
|
159
|
+
maxReplicaCount: 25
|
|
160
|
+
scalingStrategy:
|
|
161
|
+
strategy: "custom"
|
|
162
|
+
customScalingQueueLengthDeduction: 1
|
|
163
|
+
triggers:
|
|
164
|
+
- type: aws-sqs-queue
|
|
165
|
+
metadata:
|
|
166
|
+
queueURL: https://sqs.us-east-1.amazonaws.com/123456789012/transcode-jobs
|
|
167
|
+
queueLength: "1"
|
|
168
|
+
awsRegion: us-east-1
|
|
169
|
+
authenticationRef:
|
|
170
|
+
name: keda-aws-auth
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## 5. Prometheus Custom Metric Scaler
|
|
176
|
+
|
|
177
|
+
Scales HTTP microservices on rate of requests (RPS) or error ratios:
|
|
178
|
+
|
|
179
|
+
```yaml
|
|
180
|
+
apiVersion: keda.sh/v1alpha1
|
|
181
|
+
kind: ScaledObject
|
|
182
|
+
metadata:
|
|
183
|
+
name: api-service-scaler
|
|
184
|
+
namespace: production
|
|
185
|
+
spec:
|
|
186
|
+
scaleTargetRef:
|
|
187
|
+
name: api-gateway
|
|
188
|
+
minReplicaCount: 3
|
|
189
|
+
maxReplicaCount: 50
|
|
190
|
+
triggers:
|
|
191
|
+
- type: prometheus
|
|
192
|
+
metadata:
|
|
193
|
+
serverAddress: http://prometheus-k8s.monitoring.svc:9090
|
|
194
|
+
metricName: http_requests_total_rate
|
|
195
|
+
query: sum(rate(http_requests_total{job="api-gateway", status=~"2.."}[2m]))
|
|
196
|
+
threshold: "500"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## 6. Verification and Troubleshooting
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
# Check status and current active state of ScaledObjects
|
|
205
|
+
kubectl get scaledobject -n production
|
|
206
|
+
kubectl describe scaledobject order-processor-scaler -n production
|
|
207
|
+
|
|
208
|
+
# Inspect generated HPA and custom metrics
|
|
209
|
+
kubectl get hpa -n production
|
|
210
|
+
kubectl describe hpa keda-hpa-order-processor-scaler -n production
|
|
211
|
+
|
|
212
|
+
# View KEDA Operator and Metrics Server logs
|
|
213
|
+
kubectl logs -n keda -l app=keda-operator -f
|
|
214
|
+
kubectl logs -n keda -l app=keda-operator-metrics-apiserver -f
|
|
215
|
+
|
|
216
|
+
# Verify custom metrics registered in K8s APIServer
|
|
217
|
+
kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1" | jq .
|
|
218
|
+
```
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: milvus-vector-clustering
|
|
3
|
+
description: >-
|
|
4
|
+
Architects, scales, and optimizes Milvus distributed vector databases, HNSW/IVF-PQ indexing, hybrid dense-sparse search, dynamic schema partition keys, and scalar metadata filtering.
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Milvus Vector Clustering & Distributed Similarity Search
|
|
8
|
+
|
|
9
|
+
This skill guides the design, indexing, and high-throughput querying of enterprise-scale vector collections using Milvus and Zilliz Cloud.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## ⚡ Indexing Selection Matrix
|
|
14
|
+
|
|
15
|
+
| Index Type | Search Latency | Recall Rate | Memory Footprint | Best For |
|
|
16
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
17
|
+
| **`HNSW`** | Ultra-low (<5ms) | High (>98%) | High (in-memory graph) | Mission-critical search where latency is top priority. |
|
|
18
|
+
| **`IVF_FLAT`** | Medium (10-30ms) | Tunable (nprobe) | Moderate | Standard baseline for medium datasets (<10M vectors). |
|
|
19
|
+
| **`IVF_PQ`** | Low (5-15ms) | Moderate (85-92%) | Very Low (quantized) | Massive scale (100M+ vectors) with tight RAM budgets. |
|
|
20
|
+
| **`SCANN`** | Very Low (<8ms) | High (>95%) | Moderate | High-dimensional CPU-accelerated similarity search. |
|
|
21
|
+
| **`SPARSE_INVERTED_INDEX`**| Ultra-low | Exact / BM25 | Low | Sparse lexical vectors (SPLADE, BM25 hybrid ranking). |
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 🏗️ Production Collection Schema with Partition Keys
|
|
26
|
+
|
|
27
|
+
Multi-tenant applications should leverage Milvus **Partition Keys** to isolate tenant data logically without exceeding physical partition limits:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from pymilvus import (
|
|
31
|
+
connections, FieldSchema, CollectionSchema, DataType,
|
|
32
|
+
Collection, utility
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
# Connect to Milvus Cluster / Standalone
|
|
36
|
+
connections.connect(alias="default", host="localhost", port="19530")
|
|
37
|
+
|
|
38
|
+
fields = [
|
|
39
|
+
# Primary Key
|
|
40
|
+
FieldSchema(name="doc_id", dtype=DataType.VARCHAR, max_length=128, is_primary=True, auto_id=False),
|
|
41
|
+
|
|
42
|
+
# Multi-tenant Partition Key (routes queries to physical partition clusters)
|
|
43
|
+
FieldSchema(name="tenant_id", dtype=DataType.VARCHAR, max_length=64, is_partition_key=True),
|
|
44
|
+
|
|
45
|
+
# Scalar Metadata for Pre-filtering
|
|
46
|
+
FieldSchema(name="category", dtype=DataType.VARCHAR, max_length=64),
|
|
47
|
+
FieldSchema(name="created_at", dtype=DataType.INT64),
|
|
48
|
+
FieldSchema(name="is_archived", dtype=DataType.BOOL),
|
|
49
|
+
|
|
50
|
+
# Dense Vector Embedding (e.g., text-embedding-004, 768 dimensions)
|
|
51
|
+
FieldSchema(name="dense_vector", dtype=DataType.FLOAT_VECTOR, dim=768),
|
|
52
|
+
|
|
53
|
+
# Sparse Lexical Vector (e.g., SPLADE or BM25 tokens)
|
|
54
|
+
FieldSchema(name="sparse_vector", dtype=DataType.SPARSE_FLOAT_VECTOR),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
schema = CollectionSchema(fields=fields, description="Enterprise Knowledge Base Vectors", enable_dynamic_field=True)
|
|
58
|
+
collection = Collection(name="knowledge_embeddings", schema=schema)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## 🔍 Building Vector Indexes
|
|
64
|
+
|
|
65
|
+
Build indexes before loading the collection into memory:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
# 1. Dense Vector Index (HNSW for high recall & low latency)
|
|
69
|
+
dense_index_params = {
|
|
70
|
+
"metric_type": "COSINE",
|
|
71
|
+
"index_type": "HNSW",
|
|
72
|
+
"params": {
|
|
73
|
+
"M": 16, # Max outgoing links per node (16-64)
|
|
74
|
+
"efConstruction": 200 # Exploration factor during index build
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
collection.create_index(field_name="dense_vector", index_params=dense_index_params)
|
|
78
|
+
|
|
79
|
+
# 2. Sparse Vector Index
|
|
80
|
+
sparse_index_params = {
|
|
81
|
+
"metric_type": "IP", # Inner Product for sparse lexical weights
|
|
82
|
+
"index_type": "SPARSE_INVERTED_INDEX",
|
|
83
|
+
"params": {"drop_ratio_build": 0.2}
|
|
84
|
+
}
|
|
85
|
+
collection.create_index(field_name="sparse_vector", index_params=sparse_index_params)
|
|
86
|
+
|
|
87
|
+
# Load into query nodes
|
|
88
|
+
collection.load()
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## 🚀 Hybrid Search with Reciprocal Rank Fusion (RRF)
|
|
94
|
+
|
|
95
|
+
Combine dense semantic search with sparse lexical matching for optimal recall:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from pymilvus import AnnSearchRequest, RRFRanker
|
|
99
|
+
|
|
100
|
+
# Dense vector query request
|
|
101
|
+
dense_req = AnnSearchRequest(
|
|
102
|
+
data=[query_dense_embedding],
|
|
103
|
+
anns_field="dense_vector",
|
|
104
|
+
param={"metric_type": "COSINE", "params": {"ef": 64}},
|
|
105
|
+
limit=50,
|
|
106
|
+
expr='tenant_id == "org_acme" and is_archived == false'
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# Sparse vector query request
|
|
110
|
+
sparse_req = AnnSearchRequest(
|
|
111
|
+
data=[query_sparse_dict],
|
|
112
|
+
anns_field="sparse_vector",
|
|
113
|
+
param={"metric_type": "IP", "params": {"drop_ratio_search": 0.1}},
|
|
114
|
+
limit=50,
|
|
115
|
+
expr='tenant_id == "org_acme" and is_archived == false'
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Execute hybrid search with RRF reranking
|
|
119
|
+
results = collection.hybrid_search(
|
|
120
|
+
reqs=[dense_req, sparse_req],
|
|
121
|
+
rerank=RRFRanker(k=60),
|
|
122
|
+
limit=10,
|
|
123
|
+
output_fields=["doc_id", "category", "created_at"]
|
|
124
|
+
)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## 📋 Architectural Rules & Best Practices
|
|
130
|
+
|
|
131
|
+
1. **Partition Key Limits**: Use `is_partition_key=True` for tenant routing; Milvus maps millions of logical tenants into ~64-256 physical partition clusters automatically.
|
|
132
|
+
2. **Pre-Filtering Optimization**: Place high-selectivity scalar filters (`expr='category == "tech"'`) directly in the ANN search request to prune candidate sets before graph traversal.
|
|
133
|
+
3. **Compaction Management**: Call `collection.compact()` after bulk insertions or deletions to merge small segment files and purge deleted entity tombstones.
|
|
134
|
+
4. **Memory Sizing**: For HNSW, allocate approximately `(dim * 4 + M * 8) * num_vectors` bytes of RAM on QueryNodes.
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: opa-gatekeeper-policy
|
|
3
|
+
description: Authors and validates Open Policy Agent (OPA) Gatekeeper ConstraintTemplates and Rego admission policies for Kubernetes governance and security compliance.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# OPA Gatekeeper Policy
|
|
7
|
+
|
|
8
|
+
Defines declarative policy enforcement for Kubernetes clusters using Open Policy Agent (OPA) Gatekeeper ConstraintTemplates, Rego logic, and shift-left CLI testing.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Admission Control Flow
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
kubectl apply -f resource.yaml
|
|
16
|
+
│
|
|
17
|
+
▼
|
|
18
|
+
┌────────────────────────┐
|
|
19
|
+
│ Kubernetes API Server │
|
|
20
|
+
└───────────┬────────────┘
|
|
21
|
+
│ ValidatingWebhookConfiguration
|
|
22
|
+
▼
|
|
23
|
+
┌────────────────────────┐ Matches Rules?
|
|
24
|
+
│ Gatekeeper Pod │────────────────────────┐
|
|
25
|
+
│ (Admission Webhook) │ │
|
|
26
|
+
└───────────┬────────────┘ ▼
|
|
27
|
+
│ Rego Evaluation ┌────────────────────┐
|
|
28
|
+
▼ │ Reject (403) │
|
|
29
|
+
┌──────────────────────┐ │ Error & Remediation│
|
|
30
|
+
│ Constraint Templates │ └────────────────────┘
|
|
31
|
+
└──────────┬───────────┘
|
|
32
|
+
│ Passed
|
|
33
|
+
▼
|
|
34
|
+
┌──────────────────────┐
|
|
35
|
+
│ Persist to etcd │
|
|
36
|
+
└──────────────────────┘
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 2. ConstraintTemplate (Rego Engine)
|
|
42
|
+
|
|
43
|
+
Defines the reusable policy schema and Rego execution logic:
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
apiVersion: templates.gatekeeper.sh/v1
|
|
47
|
+
kind: ConstraintTemplate
|
|
48
|
+
metadata:
|
|
49
|
+
name: k8srequiredlabels
|
|
50
|
+
annotations:
|
|
51
|
+
description: "Requires all namespaces and workloads to specify standard governance labels."
|
|
52
|
+
spec:
|
|
53
|
+
crd:
|
|
54
|
+
spec:
|
|
55
|
+
names:
|
|
56
|
+
kind: K8sRequiredLabels
|
|
57
|
+
validation:
|
|
58
|
+
openAPIV3Schema:
|
|
59
|
+
type: object
|
|
60
|
+
properties:
|
|
61
|
+
labels:
|
|
62
|
+
type: array
|
|
63
|
+
items:
|
|
64
|
+
type: string
|
|
65
|
+
targets:
|
|
66
|
+
- target: admission.k8s.gatekeeper.sh
|
|
67
|
+
rego: |
|
|
68
|
+
package k8srequiredlabels
|
|
69
|
+
|
|
70
|
+
violation[{"msg": msg, "details": {"missing_labels": missing}}] {
|
|
71
|
+
provided := {label | input.review.object.metadata.labels[label]}
|
|
72
|
+
required := {label | label := input.parameters.labels[_]}
|
|
73
|
+
missing := required - provided
|
|
74
|
+
count(missing) > 0
|
|
75
|
+
msg := sprintf("Resource %v '%v' violates policy: missing required labels: %v", [
|
|
76
|
+
input.review.object.kind,
|
|
77
|
+
input.review.object.metadata.name,
|
|
78
|
+
missing
|
|
79
|
+
])
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 3. Instantiating the Constraint
|
|
86
|
+
|
|
87
|
+
Applies the template to specific resource kinds and namespaces:
|
|
88
|
+
|
|
89
|
+
```yaml
|
|
90
|
+
apiVersion: constraints.gatekeeper.sh/v1beta1
|
|
91
|
+
kind: K8sRequiredLabels
|
|
92
|
+
metadata:
|
|
93
|
+
name: require-team-and-cost-center
|
|
94
|
+
spec:
|
|
95
|
+
enforcementAction: deny # Options: deny, dryrun, warn
|
|
96
|
+
match:
|
|
97
|
+
kinds:
|
|
98
|
+
- apiGroups: ["apps"]
|
|
99
|
+
kinds: ["Deployment", "StatefulSet"]
|
|
100
|
+
- apiGroups: [""]
|
|
101
|
+
kinds: ["Namespace"]
|
|
102
|
+
excludedNamespaces:
|
|
103
|
+
- kube-system
|
|
104
|
+
- gatekeeper-system
|
|
105
|
+
parameters:
|
|
106
|
+
labels:
|
|
107
|
+
- "app.kubernetes.io/managed-by"
|
|
108
|
+
- "cost-center"
|
|
109
|
+
- "owner-team"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## 4. Container Security Constraint (Disallow Privileged)
|
|
115
|
+
|
|
116
|
+
Enforces zero-trust rootless containers:
|
|
117
|
+
|
|
118
|
+
```yaml
|
|
119
|
+
apiVersion: templates.gatekeeper.sh/v1
|
|
120
|
+
kind: ConstraintTemplate
|
|
121
|
+
metadata:
|
|
122
|
+
name: k8sdisallowprivileged
|
|
123
|
+
spec:
|
|
124
|
+
crd:
|
|
125
|
+
spec:
|
|
126
|
+
names:
|
|
127
|
+
kind: K8sDisallowPrivileged
|
|
128
|
+
targets:
|
|
129
|
+
- target: admission.k8s.gatekeeper.sh
|
|
130
|
+
rego: |
|
|
131
|
+
package k8sdisallowprivileged
|
|
132
|
+
|
|
133
|
+
violation[{"msg": msg}] {
|
|
134
|
+
c := input_containers[_]
|
|
135
|
+
c.securityContext.privileged == true
|
|
136
|
+
msg := sprintf("Privileged container '%v' is prohibited in namespace '%v'.", [
|
|
137
|
+
c.name,
|
|
138
|
+
input.review.object.metadata.namespace
|
|
139
|
+
])
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
input_containers[c] {
|
|
143
|
+
c := input.review.object.spec.template.spec.containers[_]
|
|
144
|
+
}
|
|
145
|
+
input_containers[c] {
|
|
146
|
+
c := input.review.object.spec.template.spec.initContainers[_]
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## 5. Shift-Left CI Validation with `gator` CLI
|
|
153
|
+
|
|
154
|
+
Validates Kubernetes manifests against Gatekeeper templates inside CI pipelines before merge:
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
# Test manifests directly without a live Kubernetes cluster
|
|
158
|
+
gator test \
|
|
159
|
+
--image-template=./templates/ \
|
|
160
|
+
--constraint=./constraints/ \
|
|
161
|
+
--manifests=./deploy/production/
|
|
162
|
+
|
|
163
|
+
# Run unit tests on Rego source files
|
|
164
|
+
gator verify ./policies/...
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
```yaml
|
|
168
|
+
# Gator test suite definition (suite.yaml)
|
|
169
|
+
kind: Suite
|
|
170
|
+
apiVersion: test.gatekeeper.sh/v1alpha1
|
|
171
|
+
metadata:
|
|
172
|
+
name: deployment-label-suite
|
|
173
|
+
tests:
|
|
174
|
+
- name: test-missing-labels-denied
|
|
175
|
+
template: template.yaml
|
|
176
|
+
constraint: constraint.yaml
|
|
177
|
+
cases:
|
|
178
|
+
- name: deployment-without-cost-center
|
|
179
|
+
object: bad-deployment.yaml
|
|
180
|
+
assertions:
|
|
181
|
+
- violations: yes
|
|
182
|
+
message: "missing required labels: {\"cost-center\"}"
|
|
183
|
+
- name: compliant-deployment
|
|
184
|
+
object: good-deployment.yaml
|
|
185
|
+
assertions:
|
|
186
|
+
- violations: no
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
---
|
|
190
|
+
|
|
191
|
+
## 6. Audit Cluster Violations
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
# Inspect non-compliant resources identified during continuous background audit
|
|
195
|
+
kubectl get constraints -A
|
|
196
|
+
|
|
197
|
+
# Detailed violation listing
|
|
198
|
+
kubectl get k8srequiredlabels.constraints.gatekeeper.sh require-team-and-cost-center -o yaml \
|
|
199
|
+
| yq '.status.violations[] | {resource: .name, kind: .kind, message: .message}'
|
|
200
|
+
```
|