{{ message }}
Repository navigation
Expand file tree
/
Copy pathgraph.go
More file actions
423 lines (408 loc) · 14.5 KB
/
Copy pathgraph.go
File metadata and controls
423 lines (408 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package workqueue
import (
"encoding/json"
"slices"
"sort"
"strings"
)
func resourceKey(resource Resource, condition string) string {
data, _ := canonicalValue(map[string]any{
"host": resource.Host, "repository_id": resource.RepositoryID,
"resource_id": resource.ResourceID, "kind": resource.Kind, "condition": condition,
})
return string(data)
}
func validateResource(resource Resource, pool PoolPolicy) error {
return validateResourceForHost(resource, pool, "")
}
func validateResourceForHost(resource Resource, pool PoolPolicy, selectedHost string) error {
if resource.Kind != "issue" && resource.Kind != "pull_request" {
return queueError("resource_invalid", "expected Issue or PR type")
}
host, err := resourceHost(selectedHost)
if err != nil {
return err
}
if resource.Host != host || !repoPattern.MatchString(resource.Repository) ||
!slices.Contains(pool.AllowedRepositories, resource.Repository) {
return queueError("resource_unauthorized", "host/repository is not approved")
}
for _, id := range []string{resource.RepositoryID, resource.ResourceID, resource.Number} {
if id == "" || strings.HasPrefix(id, "0") {
return queueError("resource_invalid", "resource IDs must be positive canonical decimal strings")
}
for _, char := range id {
if char < '0' || char > '9' {
return queueError("resource_invalid", "invalid decimal identity")
}
}
}
return nil
}
func (state Projection) validateGraph() error {
vertices := map[string]identitySet{}
pending := map[string]int{}
graphPools := map[string]string{}
for _, work := range state.Works {
if pool, ok := graphPools[work.GraphID]; ok && pool != work.Pool {
return queueError("graph_pool_conflict", "graph %s spans pools", work.GraphID)
}
graphPools[work.GraphID] = work.Pool
if vertices[work.GraphID] == nil {
vertices[work.GraphID] = identitySet{}
}
vertices[work.GraphID].add("work:" + work.WorkID)
if work.State != "completed" && work.State != "cancelled" || work.Barrier == "pending" {
pending[work.Pool]++
}
if len(work.DependsOn) > state.Policy.Limits.Predecessors {
return queueError("graph_limit", "too many predecessors at %s", work.NodeKey)
}
if err := state.validatePredecessors(work, vertices[work.GraphID]); err != nil {
return err
}
}
for graph, nodes := range vertices {
if len(nodes) > state.Policy.Limits.GraphNodes {
return queueError("graph_limit", "graph %s exceeds node bound", graph)
}
}
for pool, count := range pending {
if count > state.Policy.Limits.PendingNodes {
return queueError("pending_limit", "pool %s exceeds pending-node bound", pool)
}
}
return state.validateGraphCycles()
}
func (state Projection) validatePredecessors(work *WorkState, vertices identitySet) error {
seen := identitySet{}
for _, edge := range work.DependsOn {
var key string
if edge.Kind == "work" {
predecessor, ok := state.Works[edge.WorkID]
if !ok || predecessor.GraphID != work.GraphID {
return queueError("dependency_missing", "%s -> %s", work.NodeKey, edge.WorkID)
}
if edge.WorkID == work.WorkID {
return queueError("dependency_cycle", "%s -> %s", work.NodeKey, work.NodeKey)
}
key = "work:" + edge.WorkID
} else {
if edge.Resource == nil || edge.Resource.Kind != edge.Kind {
return queueError("resource_invalid", "dependency type does not match resource")
}
if err := validateResourceForHost(*edge.Resource, state.Policy.Pools[work.Pool], state.resourceHost); err != nil {
return err
}
if edge.Kind == "issue" && edge.Condition != "completed" && edge.Condition != "closed" ||
edge.Kind == "pull_request" && edge.Condition != "merged" {
return queueError("condition_invalid", "condition does not match resource type")
}
key = resourceKey(*edge.Resource, edge.Condition)
vertices.add(key)
}
if seen.contains(key) {
return queueError("dependency_duplicate", "duplicate edge at %s", work.NodeKey)
}
seen.add(key)
}
return nil
}
func (state Projection) validateGraphCycles() error {
color := map[string]int{}
path := []string{}
var visit func(string) error
visit = func(id string) error {
if color[id] == 1 {
start := slices.Index(path, id)
cycle := append(slices.Clone(path[start:]), id)
names := []string{}
for _, node := range cycle {
names = append(names, state.Works[node].NodeKey)
}
return queueError("dependency_cycle", "%s", strings.Join(names, " -> "))
}
if color[id] == 2 {
return nil
}
color[id] = 1
path = append(path, id)
for _, edge := range state.Works[id].DependsOn {
if edge.Kind == "work" {
if err := visit(edge.WorkID); err != nil {
return err
}
}
}
path = path[:len(path)-1]
color[id] = 2
return nil
}
ids := make([]string, 0, len(state.Works))
for id := range state.Works {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
if err := visit(id); err != nil {
return err
}
}
return nil
}
func (state Projection) admitWork(node WorkDefinition, commit QueueCommit, position Position) error {
pool, ok := state.Policy.Pools[node.Pool]
if !ok {
return queueError("admission_unauthorized", "principal has no pool/priority/account entitlement")
}
if err := state.validateSubmissionEntitlement(commit.Actor, node); err != nil {
return err
}
if existing := state.Works[node.WorkID]; existing != nil {
if !sameJSON(existing.WorkDefinition, node) {
return queueError("work_conflict", "immutable node %s differs", node.WorkID)
}
return nil
}
profile, profileErr := state.admissionProfile(node)
if profileErr != nil || profile.TrustDomain != node.BatchTrustDomain ||
node.WorkID != NodeID(node.GraphID, node.NodeKey) || !validKey(node.FairnessKey) {
return queueError("work_invalid", "node identity/profile/trust/account mismatch")
}
payload, err := Canonical(node.Payload)
if err != nil || int64(len(payload)) > state.Policy.Limits.PayloadBytes {
return queueError("payload_limit", "invalid or oversized Work payload")
}
if node.Subject != nil {
if err := validateResourceForHost(*node.Subject, pool, state.resourceHost); err != nil {
return err
}
}
if err := state.validateBackingIssueAdmission(node, pool); err != nil {
return err
}
if state.AdmissionPaused {
return queueError("admission_paused", "new Work admission is paused")
}
for _, other := range state.Works {
if other.GraphID == node.GraphID && other.NodeKey == node.NodeKey {
return queueError("node_conflict", "graph/node key already exists")
}
}
if node.ReplacementOf != nil {
old := state.Works[node.ReplacementOf.WorkID]
if old == nil || old.Barrier != "failed" || old.GraphID != node.GraphID ||
old.Pool != node.Pool || old.Priority != node.Priority || old.FairnessKey != node.FairnessKey {
return queueError("replacement_invalid", "replacement must inherit a delivery-failed node's scope")
}
}
state.Works[node.WorkID] = &WorkState{
WorkDefinition: node, AdmissionContract: profile.LogicalContract, State: "available", Position: position, Barrier: "none", admissionRequestID: commit.Request.ID,
}
if node.ExpiresAt != nil {
if state.expiringWorks == nil {
state.expiringWorks = map[string]bool{}
}
state.expiringWorks[node.WorkID] = true
}
return state.validateWorkAssignmentSize(node, commit, payload)
}
func (state Projection) validateWorkAssignmentSize(node WorkDefinition, commit QueueCommit, payload []byte) error {
// Valid identities forbid C0 controls; quotes/backslashes have the maximum
// canonical escaping cost per UTF-8 byte.
worstIdentity := strings.Repeat("\\", 256)
member := AssignmentClaim{
Handle: "h16", ClaimID: strings.Repeat("c", 70), WorkID: node.WorkID,
Work: payload, ResultRefs: []ResultReference{},
}
testAssignment := Assignment{
Version: Version, DispatchID: strings.Repeat("d", 70),
RequestID: worstIdentity, CommitID: worstIdentity, PolicyEpoch: commit.PolicyEpoch,
Pool: node.Pool, WorkerProfile: node.WorkerProfile,
Claims: []AssignmentClaim{},
}
var unresolvedBytes int64
for _, edge := range node.DependsOn {
if edge.Kind == "work" {
reference := ResultReference{
WorkID: edge.WorkID, ResultCommitID: worstIdentity,
Descriptor: json.RawMessage(`{}`),
}
parent := state.Works[edge.WorkID]
if parent != nil && parent.Barrier == "verified" {
reference.ResultCommitID, reference.Descriptor = parent.ResultCommitID, parent.Result
} else {
unresolvedBytes += max(0, state.Policy.Limits.ResultBytes-2)
}
member.ResultRefs = append(member.ResultRefs, reference)
}
}
testAssignment.Claims = append(testAssignment.Claims, member)
encoded, err := canonicalValue(testAssignment)
if err != nil {
return err
}
assignmentBytes := int64(len(encoded)) + unresolvedBytes
if assignmentBytes > state.Policy.Limits.AssignmentBytes {
return queueError("assignment_limit", "Work and bounded declared Result inputs cannot fit a single-Claim assignment")
}
return nil
}
func (state Projection) readiness(work *WorkState, at int64) (string, []string) {
observations := []string{}
for _, edge := range work.DependsOn {
if edge.Kind == "work" {
parent := state.Works[edge.WorkID]
if parent == nil || parent.State == "cancelled" {
return "dependency_failed", observations
}
if parent.Barrier == "failed" {
return "dependency_delivery_failed", observations
}
if parent.State != "completed" || parent.Barrier != "verified" {
return "dependency_result_unavailable", observations
}
} else {
observation := state.Observations[resourceKey(*edge.Resource, edge.Condition)]
if observation == nil || observation.State == "unknown" {
return "external_unavailable", observations
}
if observation.CredentialGeneration != state.CredentialGeneration ||
observation.ObservedAt > at ||
at-observation.ObservedAt > state.Policy.Pools[work.Pool].MaxObservationAgeMS {
return "observation_stale", observations
}
if observation.State != "ready" {
return "dependency_external_waiting", observations
}
observations = append(observations, observation.ObservationID)
}
}
return "ready", observations
}
type WorkExplanation struct {
WorkID string `json:"work_id"`
State string `json:"state"`
Barrier string `json:"barrier"`
Ready bool `json:"ready"`
SchedulingEligible bool `json:"scheduling_eligible"`
Reason string `json:"reason"`
Path []string `json:"path"`
Observations []string `json:"observations"`
}
func ExplainWork(state Projection, id string, at int64) (WorkExplanation, error) {
work := state.Works[id]
if work == nil {
return WorkExplanation{}, queueError("work_missing", "unknown Work %s", id)
}
reason, observations := state.readiness(work, at)
result := WorkExplanation{
WorkID: id, State: work.State, Barrier: work.Barrier,
Ready: work.State == "available" && reason == "ready",
Reason: reason, Observations: observations, Path: []string{work.NodeKey},
}
logical, _, accounts := state.outstanding(work.Pool)
eligibility := state.eligibility(work, at, logical, accounts)
result.SchedulingEligible = eligibility == "ready"
if result.Reason == "ready" && eligibility != "ready" {
result.Reason = eligibility
}
if work.State != "available" {
result.Reason = "ownership_" + work.State
}
current := work
for len(result.Path) <= state.Policy.Limits.GraphNodes {
var next *WorkState
for _, edge := range current.DependsOn {
if edge.Kind != "work" {
continue
}
parent := state.Works[edge.WorkID]
if parent != nil && parent.Barrier != "verified" {
next = parent
break
}
}
if next == nil {
break
}
result.Path = append(result.Path, next.NodeKey)
current = next
}
return result, nil
}
func (state Projection) recordObservation(observation Observation, commit QueueCommit) error {
key := resourceKey(observation.Resource, observation.Condition)
authorized := false
for _, pool := range state.Policy.Pools {
if validateResourceForHost(observation.Resource, pool, state.resourceHost) == nil {
authorized = true
}
}
if !authorized || observation.ObservedAt > commit.At ||
observation.CredentialGeneration != state.CredentialGeneration {
return queueError("observation_invalid", "unauthorized identity, time, or credential generation")
}
if observation.Resource.Kind == "issue" && observation.Condition != "completed" && observation.Condition != "closed" ||
observation.Resource.Kind == "pull_request" && observation.Condition != "merged" {
return queueError("condition_invalid", "observation predicate mismatch")
}
if observation.State == "ready" {
satisfies := observation.ResourceState == "closed" &&
(observation.Condition == "closed" ||
observation.Condition == "completed" && observation.StateReason == "completed")
if observation.Condition == "merged" {
satisfies = observation.Merged != nil && *observation.Merged && observation.MergeCommit != ""
}
if !satisfies || observation.ReadStatus != "ok" {
return queueError("observation_invalid", "ready must have positive typed predicate evidence")
}
}
if previous := state.ObservationIDs[observation.ObservationID]; previous != nil {
if sameJSON(previous, observation) {
return nil
}
return queueError("observation_conflict", "observation identity reused")
}
if state.ObservationWrites[key] >= state.Policy.Limits.ObservationWrites {
return queueError("observation_limit", "finite observation-write budget exhausted")
}
if current := state.Observations[key]; current != nil && observation.ObservedAt < current.ObservedAt {
return queueError("observation_invalid", "observation time moved backwards")
}
data, err := json.Marshal(observation)
if err != nil {
return err
}
if int64(len(data)) > state.Policy.Limits.EvidenceBytes {
return queueError("evidence_limit", "observation evidence too large")
}
state.ObservationWrites[key]++
state.Observations[key] = &observation
state.ObservationIDs[observation.ObservationID] = &observation
return nil
}
func (state Projection) resultRefs(work *WorkState) []ResultReference {
refs := []ResultReference{}
for _, dependency := range work.DependsOn {
if dependency.Kind == "work" {
parent := state.Works[dependency.WorkID]
refs = append(refs, ResultReference{
WorkID: parent.WorkID, ResultCommitID: parent.ResultCommitID, Descriptor: parent.Result,
})
}
}
return refs
}
func (state Projection) nodeCount() int {
nodes := identitySet{}
for _, work := range state.Works {
nodes.add("work:" + work.WorkID)
for _, dependency := range work.DependsOn {
if dependency.Kind != "work" {
nodes.add(work.GraphID + resourceKey(*dependency.Resource, dependency.Condition))
}
}
}
return len(nodes)
}
You can’t perform that action at this time.
