Skip to content

Commit f9a16f1

Browse files
Merge pull request #5 from gitcommitankit/phase-2
feat: implement AgentDeployment admission webhooks and resource quota…
2 parents 17c4678 + ddaa9c3 commit f9a16f1

21 files changed

Lines changed: 2390 additions & 70 deletions

‎.agents/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
### Serena (MCP — Semantic Code Intelligence)
4545

4646
This project supports **Serena** configured as an MCP server.
47-
Serena exposes `gopls`-backed semantic tools via the Model Context Protocol. Note that Go and `gopls` must be installed and available on `PATH` before use.
47+
Serena exposes `gopls`-backed semantic tools via the Model Context Protocol.
4848
The project is indexed and the config lives at `.serena/project.yml`.
4949

5050
**Configuration & Setup:**

‎.agents/skills/agentrax-context/SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ description: Project context and settled architecture decisions for the Agentrax
3131
| `internal/scaling/` | HPA generation and quota-capped scaling logic. |
3232
| `internal/registry/` | MCP registrar, registry HTTP handler, TTL sweep. |
3333
| `internal/quota/` | Quota arithmetic and in-flight reservation. Shared by webhook and TenantQuota reconciler. |
34+
| `internal/webhook/` | Validating and mutating admission webhooks. Lives here (not `api/`) to import `internal/quota` without creating an import cycle. |
3435
| `internal/metrics/` | Shared Prometheus client plumbing used by rollout and scaling. |
3536

3637
## Where the hard logic lives

‎api/v1alpha1/error_rate.go‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Copyright 2026.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package v1alpha1
18+
19+
import (
20+
"fmt"
21+
"math"
22+
"strconv"
23+
)
24+
25+
// ParseErrorRate parses a percentage string like "2%" and returns the float64
26+
// value (e.g. 0.02 for "2%"). Returns an error if the format is invalid.
27+
// Used by the validating webhook and the rollout threshold evaluator.
28+
func ParseErrorRate(s string) (float64, error) {
29+
if len(s) == 0 {
30+
return 0, fmt.Errorf("empty error rate string")
31+
}
32+
if s[len(s)-1] != '%' {
33+
return 0, fmt.Errorf("error rate must end with '%%': got %q", s)
34+
}
35+
// strconv.ParseFloat rejects trailing garbage (e.g. "5x") and leading
36+
// whitespace (e.g. " 5"), unlike fmt.Sscanf which silently ignores them.
37+
pct, err := strconv.ParseFloat(s[:len(s)-1], 64)
38+
if err != nil {
39+
return 0, fmt.Errorf("parsing error rate %q: %w", s, err)
40+
}
41+
// Reject non-finite values (NaN, ±Inf) that ParseFloat may return for
42+
// inputs like "NaN" or "Inf".
43+
if math.IsNaN(pct) || math.IsInf(pct, 0) {
44+
return 0, fmt.Errorf("error rate %q is not a finite number", s)
45+
}
46+
if pct < 0 || pct > 100 {
47+
return 0, fmt.Errorf("error rate %q out of range [0, 100]", s)
48+
}
49+
return pct / 100.0, nil
50+
}

‎api/v1alpha1/error_rate_test.go‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
Copyright 2026.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package v1alpha1_test
18+
19+
import (
20+
"testing"
21+
22+
agentraxv1alpha1 "github.com/gitcommitankit/agentrax/api/v1alpha1"
23+
)
24+
25+
func TestParseErrorRate(t *testing.T) {
26+
t.Parallel()
27+
tests := []struct {
28+
input string
29+
want float64
30+
wantErr bool
31+
}{
32+
{"2%", 0.02, false},
33+
{"100%", 1.0, false},
34+
{"0%", 0.0, false},
35+
{"0.5%", 0.005, false},
36+
{"", 0, true},
37+
{"5", 0, true},
38+
{"-1%", 0, true},
39+
{"101%", 0, true},
40+
{"abc%", 0, true},
41+
// trailing garbage — strconv.ParseFloat must reject these
42+
{"5x%", 0, true},
43+
// non-finite numeric input — caught by math.IsNaN / math.IsInf guard
44+
{"NaN%", 0, true},
45+
{"Inf%", 0, true},
46+
{"-Inf%", 0, true},
47+
// leading whitespace — strconv.ParseFloat must reject " 5"
48+
{" 5%", 0, true},
49+
}
50+
for _, tc := range tests {
51+
tc := tc
52+
t.Run(tc.input, func(t *testing.T) {
53+
t.Parallel()
54+
got, err := agentraxv1alpha1.ParseErrorRate(tc.input)
55+
if (err != nil) != tc.wantErr {
56+
t.Errorf("ParseErrorRate(%q) error=%v, wantErr=%v", tc.input, err, tc.wantErr)
57+
}
58+
if err == nil && abs(got-tc.want) > 1e-9 {
59+
t.Errorf("ParseErrorRate(%q) = %v, want %v", tc.input, got, tc.want)
60+
}
61+
})
62+
}
63+
}
64+
65+
func abs(f float64) float64 {
66+
if f < 0 {
67+
return -f
68+
}
69+
return f
70+
}

‎cmd/main.go‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ import (
3838

3939
agentraxv1alpha1 "github.com/gitcommitankit/agentrax/api/v1alpha1"
4040
"github.com/gitcommitankit/agentrax/internal/controller"
41+
"github.com/gitcommitankit/agentrax/internal/quota"
42+
agentraxwebhook "github.com/gitcommitankit/agentrax/internal/webhook"
4143
// +kubebuilder:scaffold:imports
4244
)
4345

@@ -59,6 +61,7 @@ func main() {
5961
var probeAddr string
6062
var secureMetrics bool
6163
var enableHTTP2 bool
64+
var gpuResourceName string
6265
var tlsOpts []func(*tls.Config)
6366
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
6467
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
@@ -70,6 +73,8 @@ func main() {
7073
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
7174
flag.BoolVar(&enableHTTP2, "enable-http2", false,
7275
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
76+
flag.StringVar(&gpuResourceName, "gpu-resource-name", quota.DefaultGPUResourceName,
77+
"Kubernetes resource name used to count GPU units in AgentDeployment resource limits.")
7378
opts := zap.Options{
7479
Development: true,
7580
}
@@ -145,6 +150,9 @@ func main() {
145150
os.Exit(1)
146151
}
147152

153+
// Shared quota enforcer used by both the webhook validator and TenantQuota reconciler.
154+
quotaEnforcer := quota.NewEnforcer(gpuResourceName)
155+
148156
if err = (&controller.AgentDeploymentReconciler{
149157
Client: mgr.GetClient(),
150158
Scheme: mgr.GetScheme(),
@@ -153,12 +161,17 @@ func main() {
153161
os.Exit(1)
154162
}
155163
if err = (&controller.TenantQuotaReconciler{
156-
Client: mgr.GetClient(),
157-
Scheme: mgr.GetScheme(),
164+
Client: mgr.GetClient(),
165+
Scheme: mgr.GetScheme(),
166+
Enforcer: quotaEnforcer,
158167
}).SetupWithManager(mgr); err != nil {
159168
setupLog.Error(err, "unable to create controller", "controller", "TenantQuota")
160169
os.Exit(1)
161170
}
171+
if err = agentraxwebhook.SetupAgentDeploymentWebhookWithManager(mgr, quotaEnforcer); err != nil {
172+
setupLog.Error(err, "unable to register webhook", "webhook", "AgentDeployment")
173+
os.Exit(1)
174+
}
162175
// +kubebuilder:scaffold:builder
163176

164177
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {

‎config/rbac/role.yaml‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ rules:
88
- agentrax.io
99
resources:
1010
- agentdeployments
11-
- tenantquotas
1211
verbs:
1312
- create
1413
- delete
@@ -21,7 +20,6 @@ rules:
2120
- agentrax.io
2221
resources:
2322
- agentdeployments/finalizers
24-
- tenantquotas/finalizers
2523
verbs:
2624
- update
2725
- apiGroups:
@@ -33,6 +31,14 @@ rules:
3331
- get
3432
- patch
3533
- update
34+
- apiGroups:
35+
- agentrax.io
36+
resources:
37+
- tenantquotas
38+
verbs:
39+
- get
40+
- list
41+
- watch
3642
- apiGroups:
3743
- apiextensions.k8s.io
3844
resources:

‎config/webhook/kustomization.yaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
resources:
2+
- manifests.yaml
3+
- service.yaml

‎config/webhook/manifests.yaml‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
apiVersion: admissionregistration.k8s.io/v1
3+
kind: MutatingWebhookConfiguration
4+
metadata:
5+
name: mutating-webhook-configuration
6+
webhooks:
7+
- admissionReviewVersions:
8+
- v1
9+
clientConfig:
10+
service:
11+
name: webhook-service
12+
namespace: system
13+
path: /mutate-agentrax-io-v1alpha1-agentdeployment
14+
failurePolicy: Fail
15+
name: magentdeployment.kb.io
16+
rules:
17+
- apiGroups:
18+
- agentrax.io
19+
apiVersions:
20+
- v1alpha1
21+
operations:
22+
- CREATE
23+
- UPDATE
24+
resources:
25+
- agentdeployments
26+
sideEffects: None
27+
---
28+
apiVersion: admissionregistration.k8s.io/v1
29+
kind: ValidatingWebhookConfiguration
30+
metadata:
31+
name: validating-webhook-configuration
32+
webhooks:
33+
- admissionReviewVersions:
34+
- v1
35+
clientConfig:
36+
service:
37+
name: webhook-service
38+
namespace: system
39+
path: /validate-agentrax-io-v1alpha1-agentdeployment
40+
failurePolicy: Fail
41+
name: vagentdeployment.kb.io
42+
rules:
43+
- apiGroups:
44+
- agentrax.io
45+
apiVersions:
46+
- v1alpha1
47+
operations:
48+
- CREATE
49+
- UPDATE
50+
resources:
51+
- agentdeployments
52+
sideEffects: None

‎config/webhook/service.yaml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
apiVersion: v1
3+
kind: Service
4+
metadata:
5+
name: webhook-service
6+
namespace: system
7+
spec:
8+
ports:
9+
- port: 443
10+
protocol: TCP
11+
targetPort: 9443
12+
selector:
13+
control-plane: controller-manager

‎go.mod‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module github.com/gitcommitankit/agentrax
33
go 1.22.0
44

55
require (
6+
github.com/go-logr/logr v1.4.2
67
github.com/onsi/ginkgo/v2 v2.19.0
78
github.com/onsi/gomega v1.33.1
89
github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.75.0
@@ -26,7 +27,6 @@ require (
2627
github.com/felixge/httpsnoop v1.0.4 // indirect
2728
github.com/fsnotify/fsnotify v1.7.0 // indirect
2829
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
29-
github.com/go-logr/logr v1.4.2 // indirect
3030
github.com/go-logr/stdr v1.2.2 // indirect
3131
github.com/go-logr/zapr v1.3.0 // indirect
3232
github.com/go-openapi/jsonpointer v0.19.6 // indirect
@@ -84,6 +84,7 @@ require (
8484
google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
8585
google.golang.org/grpc v1.65.0 // indirect
8686
google.golang.org/protobuf v1.34.2 // indirect
87+
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
8788
gopkg.in/inf.v0 v0.9.1 // indirect
8889
gopkg.in/yaml.v2 v2.4.0 // indirect
8990
gopkg.in/yaml.v3 v3.0.1 // indirect
@@ -96,4 +97,4 @@ require (
9697
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
9798
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
9899
sigs.k8s.io/yaml v1.4.0 // indirect
99-
)
100+
)

0 commit comments

Comments
 (0)