| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/equipo/planning" |
| 10 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | type PreparedBug = runnerproto.PreparedBug |
| 16 | type BugPreparer interface { |
| 17 | Prepare(context.Context, TargetBinding) (PreparedBug, error) |
| 18 | } |
| 19 | |
| 20 | func hexDigest(s string, n int) bool { |
| 21 | b, err := hex.DecodeString(s) |
| 22 | return err == nil && len(b) == n/2 && hex.EncodeToString(b) == s |
| 23 | } |
| 24 | func validPreparedBug(p PreparedBug, project Project) bool { |
| 25 | hash := sha256.Sum256(p.CheckDefinition) |
| 26 | return p.Repository == project.Repository && p.DefaultBranch == project.DefaultBranch && (hexDigest(p.BaseCommit, 40) || hexDigest(p.BaseCommit, 64)) && len(p.CheckDefinition) > 0 && len(p.CheckDefinition) <= team.MaxArtifactBytes && p.CheckDefinitionHash == hex.EncodeToString(hash[:]) && hexDigest(p.BaselineTestSetHash, 64) |
| 27 | } |
| 28 | |
| 29 | var samePreparationSelection = planning.SamePreparationSelection |
| 30 | |
| 31 | func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id string) (Task, taskOutbox, Project, error) { |
| 32 | var task Task |
| 33 | var outbox taskOutbox |
| 34 | runner, err := runnerPrincipalAt(tx, principal, s.runnerClock.Now().UTC()) |
| 35 | if err != nil { |
| 36 | return task, outbox, Project{}, err |
| 37 | } |
| 38 | if err := tx.First(&task, "id=?", id).Error; err != nil { |
| 39 | return task, outbox, Project{}, storeError(err) |
| 40 | } |
| 41 | if runner.Person != task.Requester { |
| 42 | return task, outbox, Project{}, ErrForbidden |
| 43 | } |
| 44 | project, err := bugAuthority(tx, Actor{Address: task.Requester}, task.ProjectID) |
| 45 | if err != nil { |
| 46 | return task, outbox, project, err |
| 47 | } |
| 48 | if err := tx.First(&outbox, "task_id=?", id).Error; err != nil { |
| 49 | return task, outbox, project, storeError(err) |
| 50 | } |
| 51 | if project.Revision != outbox.ProjectRevision { |
| 52 | return task, outbox, project, ErrConflict |
| 53 | } |
| 54 | config, err := bugBudget(tx, task.TeamID, task.ProjectID) |
| 55 | if err != nil { |
| 56 | return task, outbox, project, err |
| 57 | } |
| 58 | if config.Revision != outbox.BudgetRevision { |
| 59 | return task, outbox, project, ErrConflict |
| 60 | } |
| 61 | var eng, rev Selection |
| 62 | if json.Unmarshal([]byte(outbox.Engineering), &eng) != nil || json.Unmarshal([]byte(outbox.Review), &rev) != nil { |
| 63 | return task, outbox, project, ErrUnavailable |
| 64 | } |
| 65 | if eng.RunnerID != runner.ID || (rev.RunnerID != "" && rev.RunnerID != runner.ID) { |
| 66 | return task, outbox, project, ErrForbidden |
| 67 | } |
| 68 | p, err := s.planningAt(tx).Plan(task) |
| 69 | if err != nil { |
| 70 | return task, outbox, project, err |
| 71 | } |
| 72 | first, currentReview, err := s.selectionPolicy().Pair(tx, task, p, false) |
| 73 | if err != nil { |
| 74 | return task, outbox, project, err |
| 75 | } |
| 76 | if !samePreparationSelection(eng, first) || !samePreparationSelection(rev, currentReview) { |
| 77 | return task, outbox, project, ErrConflict |
| 78 | } |
| 79 | if err = subscriptionSelection(tx, eng); err != nil { |
| 80 | return task, outbox, project, err |
| 81 | } |
| 82 | return task, outbox, project, nil |
| 83 | } |
| 84 | func bugPolicy(tx *gorm.DB, task Task) (team.Policy, error) { |
| 85 | b, err := bugBudget(tx, task.TeamID, task.ProjectID) |
| 86 | if err != nil { |
| 87 | return team.Policy{}, err |
| 88 | } |
| 89 | p := (team.BudgetSet{Team: b.Team, Projects: b.Projects}).ProjectLimits(team.ProjectID(task.ProjectID)) |
| 90 | limits := team.Limits{Calls: min(24, b.Team.Calls, p.Calls), InputTokens: min(200000, b.Team.InputTokens, p.InputTokens), OutputTokens: min(40000, b.Team.OutputTokens, p.OutputTokens)} |
| 91 | return team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: min(32000, limits.InputTokens), OutputTokens: min(4000, limits.OutputTokens)}, team.Rates{}) |
| 92 | } |
| 93 | func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64, prepared PreparedBug) (Task, error) { |
| 94 | var result Task |
| 95 | err := s.write(ctx, func(tx *gorm.DB) error { |
| 96 | task, outbox, project, err := s.bugPreparationAt(tx, principal, taskID) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | if err := s.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| 101 | return err |
| 102 | } |
| 103 | if !validPreparedBug(prepared, project) { |
| 104 | return ErrInvalid |
| 105 | } |
| 106 | raw, _ := json.Marshal(prepared) |
| 107 | if outbox.State != "prepare" { |
| 108 | if outbox.Prepared != string(raw) { |
| 109 | return ErrConflict |
| 110 | } |
| 111 | if expectedRevision != task.Revision && expectedRevision != 1 { |
| 112 | return ErrConflict |
| 113 | } |
| 114 | result = task |
| 115 | return nil |
| 116 | } |
| 117 | if task.Revision != expectedRevision { |
| 118 | return ErrConflict |
| 119 | } |
| 120 | task.BaseCommit = prepared.BaseCommit |
| 121 | task.CheckDefinitionHash = prepared.CheckDefinitionHash |
| 122 | task.BaselineTestSetHash = prepared.BaselineTestSetHash |
| 123 | task.Revision++ |
| 124 | task.State = "prepared" |
| 125 | policy, err := bugPolicy(tx, task) |
| 126 | if err != nil { |
| 127 | return err |
| 128 | } |
| 129 | p, err := s.planningAt(tx).Plan(task) |
| 130 | if err != nil { |
| 131 | return err |
| 132 | } |
| 133 | spec, err := PlanJobSpec(task, project, p, policy) |
| 134 | if err != nil { |
| 135 | return err |
| 136 | } |
| 137 | specRaw, _ := json.Marshal(spec) |
| 138 | outbox.State = "job" |
| 139 | outbox.Prepared = string(raw) |
| 140 | outbox.JobSpec = string(specRaw) |
| 141 | update := tx.Model(&Task{}).Where("id=? AND revision=?", task.ID, expectedRevision).Select("BaseCommit", "CheckDefinitionHash", "BaselineTestSetHash", "Revision", "State").Updates(&task) |
| 142 | if update.Error != nil { |
| 143 | return storeError(update.Error) |
| 144 | } |
| 145 | if update.RowsAffected != 1 { |
| 146 | return ErrConflict |
| 147 | } |
| 148 | if err := tx.Model(&taskOutbox{}).Where("task_id=? AND state=?", task.ID, "prepare").Select("State", "Prepared", "JobSpec").Updates(&outbox).Error; err != nil { |
| 149 | return storeError(err) |
| 150 | } |
| 151 | if err := appendAudit(tx, Actor{Address: principal.Person}, "task.prepare", task.ID); err != nil { |
| 152 | return err |
| 153 | } |
| 154 | result = task |
| 155 | return nil |
| 156 | }) |
| 157 | if err != nil { |
| 158 | return Task{}, err |
| 159 | } |
| 160 | return result, nil |
| 161 | } |
| 162 | |
| 163 | // StartBug links the validated plan and core graph in the same commit. |
| 164 | func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64) (Task, error) { |
| 165 | if s.execution == nil { |
| 166 | return Task{}, ErrUnavailable |
| 167 | } |
| 168 | var result Task |
| 169 | err := s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 170 | task, outbox, project, err := s.bugPreparationAt(tx, principal, taskID) |
| 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | if outbox.State == "done" { |
| 175 | if expectedRevision != task.Revision && expectedRevision != task.Revision-1 { |
| 176 | return ErrConflict |
| 177 | } |
| 178 | result = task |
| 179 | return nil |
| 180 | } |
| 181 | if outbox.State != "job" || task.Revision != expectedRevision { |
| 182 | return ErrConflict |
| 183 | } |
| 184 | if err = s.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | p, err := s.planningAt(tx).Plan(task) |
| 188 | if err != nil { |
| 189 | return err |
| 190 | } |
| 191 | policy, err := bugPolicy(tx, task) |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | spec, err := PlanJobSpec(task, project, p, policy) |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | job, err := s.execution.Core.CreateJob(ctx, spec) |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | task.JobID = job.ID |
| 204 | task.Revision++ |
| 205 | task.State = "queued" |
| 206 | update := tx.Model(&Task{}).Where("id=? AND revision=?", taskID, expectedRevision).Select("JobID", "Revision", "State").Updates(&task) |
| 207 | if update.Error != nil { |
| 208 | return update.Error |
| 209 | } |
| 210 | if update.RowsAffected != 1 { |
| 211 | return ErrConflict |
| 212 | } |
| 213 | if err = tx.Model(&taskOutbox{}).Where("task_id=?", taskID).Select("State").Updates(&taskOutbox{State: "done"}).Error; err != nil { |
| 214 | return err |
| 215 | } |
| 216 | if err = appendAudit(tx, Actor{Address: principal.Person}, "task.link", taskID); err != nil { |
| 217 | return err |
| 218 | } |
| 219 | result = task |
| 220 | return nil |
| 221 | }) |
| 222 | if err != nil { |
| 223 | return Task{}, err |
| 224 | } |
| 225 | return result, nil |
| 226 | } |
| 227 | func BugJobSpec(task Task, project Project, policy team.Policy, expectedSymptom string) (team.JobSpec, error) { |
| 228 | if task.ID == "" || task.TeamID == "" || task.ProjectID <= 0 || task.ProjectID != project.ID || task.ReviewRef != "equipo/"+task.ID || task.ReviewRef == project.DefaultBranch || !validBugDescription(expectedSymptom) || !validAddress(task.Requester) || !(hexDigest(task.BaseCommit, 40) || hexDigest(task.BaseCommit, 64)) || !hexDigest(task.CheckDefinitionHash, 64) || !hexDigest(task.BaselineTestSetHash, 64) { |
| 229 | return team.JobSpec{}, ErrInvalid |
| 230 | } |
| 231 | repository, err := canonicalRepository(project.Repository) |
| 232 | if err != nil || repository != project.Repository { |
| 233 | return team.JobSpec{}, ErrInvalid |
| 234 | } |
| 235 | if _, err := CanonicalBranch(project.DefaultBranch); err != nil { |
| 236 | return team.JobSpec{}, err |
| 237 | } |
| 238 | if _, err := CanonicalBranch(task.ReviewRef); err != nil { |
| 239 | return team.JobSpec{}, err |
| 240 | } |
| 241 | if policy.Version != team.PolicyVersion || policy.MaxDepth != 0 || !policy.RequireDistinctReviewFamily || policy.Validate() != nil { |
| 242 | return team.JobSpec{}, ErrInvalid |
| 243 | } |
| 244 | caps := []team.Capability{team.CapReproduce, team.CapImplement, team.CapReview, team.CapVerify, team.CapPublish} |
| 245 | steps := make([]team.StepSpec, len(caps)) |
| 246 | for i, cap := range caps { |
| 247 | steps[i] = team.StepSpec{Key: string(cap), Capability: cap, Version: 1} |
| 248 | if i > 0 { |
| 249 | steps[i].DependsOn = []string{steps[i-1].Key} |
| 250 | } |
| 251 | } |
| 252 | return team.JobSpec{Account: team.AccountID(task.TeamID), Project: team.ProjectID(project.ID), Requester: task.Requester, RequestKey: task.ID, GrantRef: GrantRef(project.ID, task.Requester), Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, App: project.AppName, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: expectedSymptom, CheckDefinitionHash: task.CheckDefinitionHash, BaselineTestSetHash: task.BaselineTestSetHash, RequireBugFreeze: true}, Policy: policy, Steps: steps}, nil |
| 253 | } |
| 254 | |
| 255 | type BugPlanStep struct { |
| 256 | Key, Specialist, Person string |
| 257 | RunnerOnly bool |
| 258 | } |
| 259 | |
| 260 | func BugPlan(task Task) []BugPlanStep { |
| 261 | return []BugPlanStep{{Key: "reproduce", Specialist: "engineering"}, {Key: "implement", Specialist: "engineering"}, {Key: "review", Specialist: "review"}, {Key: "verify", Specialist: "review"}, {Key: "publish", RunnerOnly: true}, {Key: "merge", Person: task.MergeOwner}} |
| 262 | } |
| 263 | |