Repository navigation
Expand file tree
/
Copy pathcontroller.py
More file actions
1882 lines (1746 loc) · 100 KB
/
Copy pathcontroller.py
File metadata and controls
1882 lines (1746 loc) · 100 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2026 The RISE Project
# SPDX-License-Identifier: MIT
"""One controller tick (plan sections 5.3 and 9).
``tick`` is deterministic and side-effect free: it takes loaded state, the
policy and an ``Inputs`` snapshot collected read-only by ``collect.py``, and
returns staged state changes plus a list of *requested* effects (native Work
submissions, notifications). Nothing is executed here.
* In read-only mode (``policy.read_only``, the default) requested effects are
reported only; trusted code, not a prompt, disables every publisher.
* No model call happens on an idle tick: work is selected only when there is
an actionable planning, failure, or feedback item.
* A tick never waits for workers or builds.
"""
from __future__ import annotations
import argparse
import json
import sys
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import capacity
import ci_rerun
import collect
import commands
import engine
import handoff
import intake
import isolation
import lifecycle
import recovery
import schemas
import work as work_queue
from commands import URGENT, Command
from common import (
CONTROL_REPO,
DEV_REF,
INTAKE_LABEL,
contribution_file_id,
load_policy,
repository_root,
validate_scope_paths,
)
@dataclass
class Inputs:
now: datetime
issues: list[dict] = field(default_factory=list) # intake issues, freshly fetched
tracking_issues: dict[int, dict] = field(default_factory=dict) # every live issue's fresh description
upstream_snapshots: dict[str, dict] = field(default_factory=dict) # verified source ID / initial base
comments: list[dict] = field(default_factory=list) # {"issue_number", "comment", "event_body"}
pressure: capacity.Pressure | None = None
# What the observation of the locked upstream-PR wait found this tick, by
# contribution: the reminder states a mismatch.
handoff_observations: dict[str, dict] = field(default_factory=dict)
# The upstream PR as the observation of this tick read it, by contribution
# (``observe_ci.reads_upstream_pr_state``): whether it is open decides the
# resume and the restart that depend on it.
upstream_pr_observations: dict[str, dict] = field(default_factory=dict)
resolution_evidence: dict[str, dict] = field(default_factory=dict)
acceptances: dict[int, int] = field(default_factory=dict) # issue id -> accepting actor id
requests_today: dict[int, int] = field(default_factory=dict) # actor id -> count
# The queue graphs (``work.graph_id``) of Work that already returned a
# Result or that the queue holds as terminal. A terminal graph is never
# submitted again: Work allocated under one takes `allocate_work_retry`
# or `exhaust_work_recovery` in the same tick.
spent_graphs: frozenset[str] = frozenset()
# The handoff workflow runs that are not completed, by operation (run id);
# None when the run list was not read this tick.
handoff_runs: dict[str, int] | None = None
@dataclass
class TickResult:
staged: list[tuple[str, dict]] = field(default_factory=list) # (kind, record)
requested_effects: list[dict] = field(default_factory=list)
report: dict[str, Any] = field(default_factory=dict)
def stage(self, kind: str, record: dict) -> None:
self.staged.append((kind, record))
def _iso(t: datetime) -> str:
return t.isoformat()
def _actionable(c: dict) -> str | None:
"""What a coding agent could usefully do now, or None (no AI on idle)."""
if c["paused"] or c["phase"] in lifecycle.TERMINAL | {"parked"}:
return None
if c.get("pending_publication"):
return None # a delivered proposal is still being published; never re-run the agent for it
if c.get("active_work"):
return None # a task was already requested for this contribution; wait for its outcome
if c.get("active_operation_id") or c["activity"] in ("agent_running", "waiting_human",
"waiting_ci", "waiting_capacity"):
return None
if c["phase"] == "upstream_review" and c["activity"] == "fix_needed":
return "upstream_revision"
if engine.state_key(c) == "handoff.review_due":
return work_queue.SUBMISSION_REWRITE
if engine.state_key(c) == "handoff.review_pending":
return work_queue.SUBMISSION_REVIEW
if c["phase"] == "development" and c["activity"] == "fix_needed":
return "development_repair"
if c["phase"] in ("queued", "planning") and c["activity"] == "idle":
return "planning"
return None
# The deadline recorded with requested Work (`active_work.deadline_at`). No
# row reads it: Work whose graph ends without a usable Result is recovered by
# `allocate_work_retry` and `exhaust_work_recovery`.
WORK_DEADLINE_HOURS = 6
PRIORITY = {"upstream_revision": 0, "submission_rewrite": 0, "submission_review": 0,
"development_repair": 1,
"development_patch": 2, "planning": 3}
WRITE_KINDS = {"upstream_revision", "development_repair", "development_patch"}
# The rows of the table that allocate due Work, by the state it is due in, in
# the order they are tried; their guards are exclusive. A request in
# `queued.idle` first takes `begin_planning`, in the tick that allocates
# the planning Work.
ALLOCATIONS = {
"planning.idle": ("dispatch_planning",),
"development.fix_needed": ("request_repair", "request_patch"),
"handoff.review_due": ("request_submission_rewrite",),
"handoff.review_pending": ("request_submission_review",),
"upstream_review.fix_needed": ("request_upstream_revision", "request_review_revision"),
}
# The rows taken instead when a budget of that Work is exhausted. They need no
# worker slot and are taken as soon as their guard holds.
EXHAUSTIONS = {
"planning.idle": ("exhaust_work_total",),
"development.fix_needed": ("exhaust_work_total", "refresh_on_exhaustion",
"exhaust_repair_attempts"),
"handoff.review_due": ("exhaust_work_total",),
"handoff.review_pending": ("exhaust_work_total",),
"upstream_review.fix_needed": ("exhaust_repair_attempts",),
}
# The facts the controller establishes for an allocation it is about to take.
ALLOCATION_FACTS = frozenset({"worker_slot_free", "capacity_available"})
def task_for(verb: str, record: dict) -> str:
"""The task an allocation row asks a worker for. ``request_patch`` asks
for a repair when the record holds pending feedback for it to answer."""
if verb == "dispatch_planning":
return "planning"
if verb == "request_submission_rewrite":
return work_queue.SUBMISSION_REWRITE
if verb == "request_submission_review":
return work_queue.SUBMISSION_REVIEW
if verb in ("request_upstream_revision", "request_review_revision"):
return "upstream_revision"
if verb == "request_repair" or record.get("pending_feedback_evidence_ids"):
return "development_repair"
return "development_patch"
SOURCE_UNVERIFIED = "source verification unavailable"
def _bind_source(c: dict, inputs: Inputs, by_id: dict[str, dict], res: TickResult,
source_blocked: dict[str, dict | None], policy: dict, now: str) -> None:
"""Bind the unbound upstream identity and base of ``c`` from this tick's
verified snapshot of its upstream; a changed identity pauses it, and a
source that cannot be verified blocks it for the tick. ``source_blocked``
maps each blocked contribution to the snapshot that could not be read,
or ``None``; a contribution is reported as deferred once, when it is
blocked. A snapshot that was read starts ``source_reads`` again."""
cid = c["contribution_id"]
rep = res.report
snapshot = inputs.upstream_snapshots.get(c["upstream"]["full_name"])
if snapshot is None:
return
if snapshot.get("error"):
source_blocked[cid] = snapshot
rep["deferred"].append({"contribution": cid, "why": SOURCE_UNVERIFIED})
return
if _upstream_read_resume(c) == "resume_renamed_upstream" \
and c["upstream"].get("repository_id") is None:
# The wait a renamed repository caused, for a request whose id GitHub
# did not give: whatever repository is now read under the recorded
# name may be another one, so it is never bound without a human. A
# resume ends the wait, and the request is bound once it is due.
source_blocked[cid] = None
rep["deferred"].append({"contribution": cid,
"why": "the renamed upstream repository has no recorded id; "
"a resume continues"})
return
budget = c.get("budget") or {}
if budget.get("source_unavailable") or any(k in budget for k in engine.SOURCE_READ_FIELDS):
restarted = {k: v for k, v in budget.items() if k not in engine.SOURCE_READ_FIELDS}
c = engine.record_beside(c, "upstream_read", now=now,
budget=dict(restarted, source_unavailable=0))
by_id[cid] = c
res.stage("contributions", c)
current = c["upstream"].get("repository_id")
if current is not None and current != snapshot["repository_id"]:
source_blocked[cid] = None
# The table verb for a changed identity sets the paused flag
# with the controller's reason, clears the requested Work and
# what is held for publication, and keeps the state (from an
# `agent_running` state, the state in which the Work is due).
cause = f"upstream-identity-{snapshot['repository_id']}"
out = engine.apply_transition(
c, "pause_on_identity_change", policy=policy, now=now, cause_id=cause,
facts={"upstream_identity_changed"})
if out.accepted:
by_id[cid] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
return
if c["upstream"].get("base_sha") is None \
and c["upstream"].get("base_ref") not in (None, snapshot["base_ref"]):
# The base is bound from a snapshot of the branch the record names
# (the target branch the request asked for) only; a snapshot read
# at another branch binds nothing, and a later tick reads it again.
source_blocked[cid] = None
rep["deferred"].append({"contribution": cid,
"why": "upstream snapshot is not of the requested base branch"})
return
updated = dict(c["upstream"])
for key in ("repository_id", "base_ref", "base_sha"):
if updated.get(key) is None:
updated[key] = snapshot[key]
if updated != c["upstream"]:
changed = engine.record_beside(c, "upstream_identity_bound", now=now,
upstream=updated)
by_id[cid] = changed
res.stage("contributions", changed)
# The states in which the record follows a base branch the upstream renamed
# while the upstream PR is open, each with the row it takes.
RENAMED_BASE_ROWS = {"upstream_review.waiting_ci": "follow_renamed_base",
"upstream_review.fix_needed": "follow_renamed_base",
"upstream_review.waiting_human": "resume_renamed_base"}
def _follow_renamed_base(c: dict, snapshot: dict, by_id: dict[str, dict], operations: dict,
res: TickResult, policy: dict, now: str) -> bool:
"""Follow a base branch the upstream renamed while the upstream PR is
open: the collector verified that the PR the record names is open, that
it targets the new name, and that the new name contains the recorded base
commit (``snapshot["pr_base"]``). ``True`` once a row was taken."""
verb = RENAMED_BASE_ROWS.get(engine.state_key(c))
pr_base = snapshot.get("pr_base") or {}
upstream, pr = c["upstream"], c.get("upstream_pr") or {}
if verb is None or not pr_base or snapshot.get("base_ref") != upstream.get("base_ref") \
or pr_base.get("pr_id") != pr.get("id") \
or pr_base.get("base_sha") != upstream.get("base_sha") \
or pr_base.get("base_ref") != snapshot.get("renamed_to"):
return False
details = {"base_ref": upstream["base_ref"], "renamed_to": pr_base["base_ref"],
"pr_number": pr.get("number"), "base_sha": upstream["base_sha"]}
out = engine.apply_transition(
c, verb, policy=policy, now=now, facts={"base_renamed_in_pr"},
open_operations=_open_operations(c, operations),
values={"upstream.base_ref": pr_base["base_ref"],
"upstream_pr.base_ref": pr_base["base_ref"]},
cause_id=f"base-renamed-{pr_base['base_ref'][:100]}", details=details)
if not out.accepted:
return False
by_id[c["contribution_id"]] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
res.report.setdefault("base_branch_renamed", []).append(
{"contribution": c["contribution_id"], **details})
return True
def _upstream_read_resume(c: dict) -> str | None:
"""The row that ends the wait of ``c`` once the upstream is read again:
``resume_upstream_read`` for a wait failed reads caused (the counter
``source_reads``), ``resume_renamed_upstream`` for the wait a renamed
repository caused (``upstream_unavailable`` with no counter), and
``None`` for any other wait."""
pending = c.get("pending_human_action") or {}
if engine.state_key(c) not in lifecycle.UPSTREAM_READ_RESUMES:
return None
if pending.get("counter") == "source_reads":
return "resume_upstream_read"
if pending.get("kind") == lifecycle.UPSTREAM_UNAVAILABLE and pending.get("counter") is None:
return "resume_renamed_upstream"
return None
def _resume_upstream_read(c: dict, snapshot: dict, by_id: dict[str, dict], operations: dict,
res: TickResult, policy: dict, now: str) -> None:
"""End a wait that failed reads caused, or that a renamed repository
caused, once this tick read the upstream again under its recorded name
(``_upstream_read_resume``). A snapshot of another branch than the record
names, or of another repository id, says nothing about it, and a paused
or non-quiescent record keeps the wait."""
verb = _upstream_read_resume(c)
if verb is None or snapshot.get("error") or snapshot.get("repository_id") is None \
or snapshot.get("base_ref") != c["upstream"].get("base_ref") \
or snapshot.get("repository_id") != c["upstream"].get("repository_id"):
return
ops = _open_operations(c, operations)
if engine.refusal(c, verb, policy=policy, now=now,
facts={"upstream_read_again"}, open_operations=ops):
return
pending = c["pending_human_action"]
details = {"base_ref": c["upstream"].get("base_ref"), "pending_human_action": pending["kind"],
"repository": c["upstream"]["full_name"]}
out = engine.apply_transition(c, verb, policy=policy, now=now,
facts={"upstream_read_again"}, open_operations=ops,
cause_id=f"upstream-read-r{c['revision']}", details=details)
if not out.accepted:
return
by_id[c["contribution_id"]] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
res.report.setdefault("upstream_read_again", []).append(
{"contribution": c["contribution_id"], **details})
def _same_repository_renamed(c: dict, snapshot: dict) -> bool:
"""Whether GitHub answered for the recorded repository under another
name: the snapshot names the new name, and the repository id it read is
the recorded one (or none is bound yet, as for a request in
`queued.idle`)."""
if not snapshot.get("renamed_repository") or "renamed_repository_id" not in snapshot:
return False
recorded = c["upstream"].get("repository_id")
return recorded is None or recorded == snapshot["renamed_repository_id"]
def _replace_rename_wait(c: dict, snapshot: dict, by_id: dict[str, dict], operations: dict,
res: TickResult, policy: dict, now: str) -> None:
"""In the wait a renamed repository caused, once GitHub answers for the
recorded repository id under its recorded name again but says that the
base branch is missing or was renamed: ``require_base_branch`` replaces
the wait with the wait of the base branch, with the entry it posts from
the state the step was due in. A snapshot of another branch or of
another repository id says nothing about it, and a paused or
non-quiescent record keeps the wait."""
recorded = c["upstream"].get("repository_id")
if not snapshot.get("missing") or recorded is None \
or snapshot.get("repository_id") != recorded \
or snapshot.get("base_ref") != c["upstream"].get("base_ref"):
return
details: dict[str, Any] = {"base_ref": snapshot["base_ref"], "why": snapshot["error"]}
if snapshot.get("renamed_to"):
details["renamed_to"] = snapshot["renamed_to"]
out = engine.apply_transition(c, "require_base_branch", policy=policy, now=now,
facts={"base_branch_missing"},
open_operations=_open_operations(c, operations),
cause_id=f"source-r{c['revision']}", details=details)
if not out.accepted:
return
by_id[c["contribution_id"]] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
res.report.setdefault("base_branch_unavailable", []).append(
{"contribution": c["contribution_id"], "verb": "require_base_branch",
**{k: v for k, v in details.items() if k != "why"}})
def _defer(res: TickResult, cid: str, why: str) -> None:
"""Report ``cid`` as deferred for ``why``: the entry `_bind_source`
already made for it in this tick is made more precise, so that a
contribution is reported as deferred once."""
for entry in res.report["deferred"]:
if entry["contribution"] == cid and entry["why"] == SOURCE_UNVERIFIED:
entry["why"] = why
return
res.report["deferred"].append({"contribution": cid, "why": why})
def _source_unavailable(c: dict, snapshot: dict, by_id: dict[str, dict], operations: dict,
res: TickResult, policy: dict, now: str) -> None:
"""Take the row for an upstream repository or base branch that could not
be read in this tick, in a state of ``lifecycle.BASE_BRANCH_WAITS``. A
request in `queued.idle` takes it from there; only a paused or
non-quiescent contribution, or one in another state, stays deferred.
A snapshot read at another branch than the record names says nothing
about the record's branch: the collector reads one branch per upstream,
and that snapshot never leads this record to a wait or a charge."""
cid = c["contribution_id"]
if _upstream_read_resume(c) == "resume_renamed_upstream":
_replace_rename_wait(c, snapshot, by_id, operations, res, policy, now)
return
if engine.state_key(c) not in lifecycle.BASE_BRANCH_WAITS:
return
if "ref" in snapshot and snapshot["ref"] != c["upstream"].get("base_ref"):
_defer(res, cid, "upstream snapshot is not of the recorded base branch")
return
ops = _open_operations(c, operations)
base_ref = snapshot.get("base_ref") or c["upstream"].get("base_ref")
details: dict[str, Any] = {"base_ref": base_ref, "why": snapshot["error"]}
values: dict[str, Any] = {}
if snapshot.get("missing"):
verb, facts = "require_base_branch", {"base_branch_missing"}
if snapshot.get("renamed_to"):
details["renamed_to"] = snapshot["renamed_to"]
elif _same_repository_renamed(c, snapshot):
# GitHub answers for the same repository id under another name: a
# definitive answer, so the contribution waits at once, with no
# counter, instead of spending the retry window on a read that
# cannot change.
verb = "require_renamed_upstream"
facts = {"base_branch_unread", "upstream_repository_unread", "upstream_repository_renamed"}
details.update({"repository": c["upstream"]["full_name"],
"renamed_repository": snapshot["renamed_repository"]})
# The id GitHub answered for is recorded, so that the wait ends only
# once the same repository is read under the recorded name again: a
# request not bound yet is never bound to another repository that
# took the name later.
recorded = c["upstream"].get("repository_id")
values["upstream.repository_id"] = recorded if recorded is not None \
else snapshot.get("renamed_repository_id")
if values["upstream.repository_id"] is not None:
details["repository_id"] = values["upstream.repository_id"]
else:
current_repository = snapshot.get("scope") == "repository"
budget = c.get("budget") or {}
count = int(budget.get("source_unavailable", 0))
limit = lifecycle.budget_limit("source_reads", policy)
spent = engine.source_reads_spent(c, policy, now)
counted = engine.source_read_counted(c, policy, now)
if not counted and not spent:
# Counted at most once per spacing slot: a read in the same slot
# writes nothing, so a burst of ticks adds no events and no
# commits. A read that exhausts the budget is never held back.
_defer(res, cid, "upstream read failed; counted at most once per spacing")
return
# The counted failed reads of the run, this one included when it is
# counted, and how many of them could not read the repository
# itself: the exhaustion names the cause of most of the run, not of
# the last read only.
failures = count + (1 if counted else 0)
repository_failures = int(budget.get("source_unavailable_repository", 0)) \
+ (1 if current_repository and counted else 0)
if spent:
repository = 2 * repository_failures > failures
verb = "require_upstream_access" if repository else "exhaust_source_reads"
else:
repository = current_repository
verb = "record_source_unavailable"
facts = {"base_branch_unread"} | ({"upstream_repository_unread"} if repository else set())
details.update({"count": failures, "repository_failures": repository_failures,
"limit": limit,
"since": budget.get("source_unavailable_since") or now,
"minutes": int(lifecycle.policy_value(
policy, lifecycle.SOURCE_READS_MINUTES_KEY))})
if repository or current_repository:
details["repository"] = c["upstream"]["full_name"]
if snapshot.get("renamed_repository"):
details["renamed_repository"] = snapshot["renamed_repository"]
out = engine.apply_transition(c, verb, policy=policy, now=now, facts=facts, values=values,
open_operations=ops, cause_id=f"source-r{c['revision']}",
details=details)
if not out.accepted:
return
by_id[cid] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
if verb != "record_source_unavailable":
res.report.setdefault("base_branch_unavailable", []).append(
{"contribution": cid, "verb": verb,
**{k: v for k, v in details.items() if k != "why"}})
def tick(*, contributions: dict[str, dict], operations: dict[str, dict], consumed: dict[int, dict],
projects: dict[str, dict], policy: dict, inputs: Inputs,
skip: frozenset[str] = frozenset(), evidence: dict[str, dict] | None = None) -> TickResult:
"""``evidence`` is the store's evidence by id, from which the failing CI
job of a head is decided when Work is due. ``skip`` names the
contributions this tick does not process: nothing
is staged or requested for them, and a command on their tracking issue
is left unconsumed for the next tick. They still count as existing
contributions (worker slots, one active contribution per upstream).
Every step that works on one contribution runs in an
``isolation.contribution`` block."""
res = TickResult()
now = _iso(inputs.now)
by_id = {c["contribution_id"]: c for c in contributions.values()}
rep = res.report
rep.update({"at": now, "policy_version": policy["policy_version"],
"read_only": policy["read_only"], "commands": [], "intake": [],
"operations": [], "selected": [], "deferred": [], "alerts": []})
# 1. Intake first, so a command posted on a brand-new request applies to it.
parked = [p["upstream"]["full_name"] for p in projects.values() if p.get("parked")]
active = {c["upstream"]["full_name"]: c["contribution_id"] for c in by_id.values()
if c["phase"] not in lifecycle.TERMINAL}
known = [c["tracking_issue"]["id"] for c in by_id.values()]
for issue in inputs.issues:
if issue.get("id") in known:
continue # already a contribution; the form is not re-read
try:
req = intake.parse_request(issue, policy)
except intake.IntakeError as e:
rep["intake"].append({"issue": issue["number"], "decision": "invalid", "detail": str(e)})
continue
decision, detail = intake.admission_decision(
req, accepted_by=inputs.acceptances.get(req.issue_id), policy=policy,
active_by_upstream=active, parked_upstreams=parked, known_issue_ids=known,
requests_today_by_actor=inputs.requests_today.get(req.actor_id, 0))
rep["intake"].append({"issue": req.issue_number, "decision": decision, "detail": detail})
if decision != "accept":
continue
project_id = contribution_file_id(req.upstream.replace("/", "--").lower())
cid = f"{project_id}/{req.issue_number}"
if cid in skip:
rep["intake"][-1] = {"issue": req.issue_number, "decision": "deferred",
"detail": "the contribution is not processed in this tick"}
continue
rec = lifecycle.new_contribution(
contribution_id=cid, project_id=project_id,
issue={
"id": req.issue_id,
"number": req.issue_number,
"url": f"https://github.com/{CONTROL_REPO}/issues/{req.issue_number}",
"description": req.body,
"description_digest": req.digest,
"notes": req.notes,
},
upstream=req.upstream,
distributions=list(req.distributions), base_ref=req.target_branch,
policy_id=policy["policy_version"], now=now)
by_id[cid] = rec
active[req.upstream] = cid
known.append(req.issue_id)
res.stage("contributions", rec)
res.stage("events", {"schema_version": 1, "contribution_id": cid, "sequence": 0, "at": now,
"kind": "intake:accepted", "from": {}, "to": {"phase": "queued"},
"cause": {"type": "observation", "id": f"issue-{req.issue_id}"},
"revision_bumped": False})
proj = projects.get(project_id) or {
"schema_version": 1, "project_id": project_id,
"upstream": {"repository_id": None, "full_name": req.upstream},
"distributions": list(req.distributions), "parked": False, "parked_reason": None,
"contribution_ids": [], "active_contribution_id": None, "prerequisites": [],
"plan_evidence_id": None, "release_observation": None, "updated_at": now}
proj = dict(proj, contribution_ids=proj["contribution_ids"] + [cid],
active_contribution_id=cid, updated_at=now)
projects[project_id] = proj
res.stage("projects", proj)
# Removing the intake label withdraws only an accepted request that has
# not requested any Work yet (`withdraw_request`, guarded by no Work, no
# plan, and no fork). Once Work exists, explicit lifecycle commands are
# required so an unlabeled event cannot silently stop work.
for cid, c in list(by_id.items()):
if cid in skip:
continue
with isolation.contribution(cid, "intake_label"):
issue = inputs.tracking_issues.get(c["tracking_issue"]["number"])
labels = {label.get("name") if isinstance(label, dict) else label
for label in (issue or {}).get("labels", [])}
if issue is None or INTAKE_LABEL in labels \
or engine.state_key(c) != "queued.idle":
continue
out = engine.apply_transition(c, "withdraw_request", policy=policy, now=now,
cause_id=f"issue-{c['tracking_issue']['id']}",
facts={"intake_label_removed"})
if not out.accepted:
continue
changed = out.record
by_id[cid] = changed
active.pop(c["upstream"]["full_name"], None)
res.stage("contributions", changed)
res.stage("events", out.event)
project = projects.get(c["project_id"])
if project and project.get("active_contribution_id") == cid:
project = dict(project, active_contribution_id=None, updated_at=now)
projects[c["project_id"]] = project
res.stage("projects", project)
rep["intake"].append({"issue": c["tracking_issue"]["number"], "decision": "cancelled",
"detail": f"{INTAKE_LABEL} label removed before Work admission"})
# Bind initially unspecified source identities/bases from trusted API data,
# never from the model's plan. Already-bound bases remain immutable. A
# parked upstream is not read here: it is bound again below, in the same
# tick, once a restart left `parked` and cleared it.
source_blocked: dict[str, dict | None] = {}
for cid, c in list(by_id.items()):
if cid in skip or c["phase"] == "parked":
continue
with isolation.contribution(cid, "source_identity"):
_bind_source(c, inputs, by_id, res, source_blocked, policy, now)
# 2. Authorized commands, urgent stops first, all before any work is selected.
decisions = []
for item in inputs.comments:
d = intake.accept_command(comment=item["comment"], issue_number=item["issue_number"],
event_body=item.get("event_body"), policy=policy,
consumed=consumed, now=now)
decisions.append(d)
decisions.sort(key=lambda d: 0 if d.command and d.command.verb in URGENT else 1)
for d in decisions:
if d.receipt["comment_id"] in consumed and not d.accepted:
rep["commands"].append({"comment": d.receipt["comment_id"], "result": d.reason})
continue
target = _command_target(d, by_id, operations)
if target in skip:
# Left unconsumed: the next tick reads the comment again.
rep["commands"].append({"comment": d.receipt["comment_id"], "result": "deferred",
"reason": "the contribution is not processed in this tick"})
continue
receipt = dict(d.receipt)
if d.accepted and target is not None:
# A stop command that cannot be applied makes its contribution
# errored: the tick is computed again without it, so nothing is
# launched for it.
with isolation.contribution(target, "command"):
receipt = _apply(d.command, receipt, by_id, operations, inputs, res, now, policy)
elif d.accepted:
receipt = _apply(d.command, receipt, by_id, operations, inputs, res, now, policy)
consumed[receipt["comment_id"]] = receipt
res.stage("commands", receipt)
rep["commands"].append({"comment": receipt["comment_id"], "result": receipt["result"],
"reason": receipt.get("reason")})
# A restart from `parked` (`restart_generation`) cleared the upstream
# identity and base: they are bound in this tick, before any Work is
# selected, from the snapshot read for the refresh. Every row that
# allocates Work requires them; without a snapshot the record waits and
# a later tick binds them.
for cid, c in list(by_id.items()):
if cid in skip or cid in source_blocked or c["phase"] in lifecycle.TERMINAL | {"parked"} \
or all(c["upstream"].get(k) is not None
for k in ("repository_id", "base_ref", "base_sha")):
continue
with isolation.contribution(cid, "source_identity"):
_bind_source(c, inputs, by_id, res, source_blocked, policy, now)
# An upstream base branch that could not be read. In upstream review, a
# branch renamed while the upstream PR is open is followed
# (`follow_renamed_base`, `resume_renamed_base`). Where Work or the fork
# provisioning is due otherwise: `require_base_branch` once the upstream
# answered that it is missing, `require_renamed_upstream` at once when
# GitHub names the same repository otherwise, `exhaust_source_reads` (or
# `require_upstream_access` when most counted reads could not read the
# repository itself) once `source_reads` is exhausted, the charge of
# `record_source_unavailable` otherwise, at most once per spacing.
for cid, snapshot in list(source_blocked.items()):
if cid in skip or snapshot is None:
continue
with isolation.contribution(cid, "source_unavailable"):
if not _follow_renamed_base(by_id[cid], snapshot, by_id, operations, res, policy, now):
_source_unavailable(by_id[cid], snapshot, by_id, operations, res, policy, now)
# A wait that failed reads caused ends once the upstream is read again
# (`resume_upstream_read`), and the wait a renamed repository caused
# once GitHub answers for it under its recorded name again
# (`resume_renamed_upstream`), after the commands, so that a resume
# posted in the same tick is taken as posted.
for cid, c in list(by_id.items()):
if cid in skip or cid in source_blocked:
continue
snapshot = inputs.upstream_snapshots.get(c["upstream"]["full_name"])
if snapshot is None:
continue
with isolation.contribution(cid, "upstream_read_again"):
_resume_upstream_read(c, snapshot, by_id, operations, res, policy, now)
# 2b. Reminders of a pending human step: the table's `record_reminder`, in
# every state of kind gate, human_wait, or locked, once
# `human_sla_business_days.reminder` business days have passed since the
# request or the last reminder. Suppressed while paused.
reminders = []
reminder_states = set(lifecycle.rule_states("record_reminder"))
for cid, c in list(by_id.items()):
if cid in skip or engine.state_key(c) not in reminder_states:
continue
with isolation.contribution(cid, "reminder"):
if engine.refusal(c, "record_reminder", policy=policy, now=now):
continue
out = engine.apply_transition(c, "record_reminder", policy=policy, now=now,
cause_id=f"reminder-{c['revision']}",
details=reminder_details(
c, operations, inputs.handoff_observations.get(cid)))
by_id[cid] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
reminders.append({"contribution": cid, "state": engine.state_key(c),
"pending_human_action": c["pending_human_action"]["kind"]})
if reminders:
rep["reminders"] = reminders
# 3. Uncertain operations before any replacement.
blocked_by_op: set[str] = set()
for op in operations.values():
if op["contribution_id"] in skip:
continue
with isolation.contribution(op["contribution_id"], "operation_recovery"):
if op["status"] in recovery.OPEN:
blocked_by_op.add(op["contribution_id"])
due = recovery.next_discovery_at(op, policy)
rep["operations"].append({"id": op["operation_id"], "status": op["status"],
"next_discovery": due.isoformat() if due else None})
for a in recovery.alerts(op, inputs.now):
rep["alerts"].append({"operation": op["operation_id"], "alert": a})
# The handoff operations. In a handoff state that runs one, the controller
# records the intent of the next attempt when none is open, and launches
# the planned attempt through the trusted workflow. No row of the table
# launches it: its launches are counted like `operation_launch`, on the
# operation, and it is not launched while the contribution is paused.
res.report["handoff_requests"] = []
for cid, c in list(by_id.items()):
if cid in skip or engine.state_key(c) not in handoff.KINDS:
continue
with isolation.contribution(cid, "handoff_operation"):
_launch_handoff(c, by_id, operations, res, inputs, now, policy, evidence or {})
# Provisioning is a trusted administrative workflow, not a model task.
# Persist its normal operation intent before dispatch, with no second queue.
# In `provisioning.idle` the table's rows launch it: `start_operation`
# within `operation_launch` (counted on the operation), and
# `require_provisioning_intervention` once that budget is exhausted.
res.report["provision_requests"] = []
for cid, c in list(by_id.items()):
if cid in skip:
continue
with isolation.contribution(cid, "provisioning"):
operation = operations.get(c.get("active_operation_id"))
if operation and operation.get("kind") == "fork_provision" \
and operation.get("status") == "planned":
attempts = recovery.launch_attempts(operation)
due = attempts == 0 or (
(inputs.now - datetime.fromisoformat(operation["updated_at"])).total_seconds()
>= LAUNCH_INTERVAL_SECONDS)
# Only `provisioning.idle` has a row that launches it; a wait
# of the table is left only by its own rows.
if due and _launch_provisioning(c, operation, by_id, operations, inputs, res, now,
policy):
break
for cid, c in list(by_id.items()):
if res.report["provision_requests"]:
break
if cid in skip:
continue
with isolation.contribution(cid, "provisioning"):
if engine.state_key(c) != "provisioning.idle" or c.get("paused") \
or recovery.is_open(operations.get(c.get("active_operation_id"))) \
or (c.get("active_operation_id") and c["active_operation_id"] not in operations) \
or cid in source_blocked:
continue
if not c.get("plan_evidence_id") or not c.get("admission_class") \
or not c.get("scope_paths") \
or not c["upstream"].get("repository_id") or not c["upstream"].get("base_sha"):
rep["deferred"].append({"contribution": cid, "why": "provisioning prerequisites missing"})
continue
ok, why = capacity.admit_expensive(inputs.pressure or capacity.Pressure(ok=False, reason="no usage data"),
reserved=capacity.reserved_jobs(operations.values()), estimated_jobs=1, policy=policy)
if not ok:
rep["deferred"].append({"contribution": cid, "why": why})
continue
fork = c.get("fork") or {}
op = recovery.plan(contribution_id=cid, revision=c["revision"], kind="fork_provision",
policy_version=policy["policy_version"], reason_ids=[c["plan_evidence_id"]],
target={"repository": "riseproject-upstreaming/" + c["upstream"]["full_name"].split('/', 1)[1],
"repository_id": fork.get("repository_id"), "ref": DEV_REF,
"expected_head": fork.get("head_sha"), "base_sha": c["upstream"]["base_sha"]},
proposed={"commit": c["upstream"]["base_sha"], "marker": f"provision:{cid}:{c['revision']}"},
capacity={"selector": "ubuntu-24.04-riscv", "estimated_jobs": 1,
"estimated_minutes": 10, "observed_run_ids": []}, now=now)
if op["operation_id"] in operations:
rep["deferred"].append({"contribution": cid, "why": "existing provisioning operation requires reconciliation"})
continue
# The intent is recorded and launched in the same tick.
planned = engine.record_beside(c, "operation_planned", now=now,
active_operation_id=op["operation_id"])
if not _launch_provisioning(planned, op, by_id, operations, inputs, res, now, policy,
capacity_checked=True):
raise lifecycle.TransitionError(
f"start_operation refused for a new provisioning intent of {cid}")
# A published development head gets a same-fork development PR before CI
# observation. Persist intent first; the trusted workflow creates/discovers
# exactly riscv64-dev -> the frozen upstream base ref and returns a receipt.
# No row of the table creates the development PR: the operation is
# planned in `development.waiting_ci`, which it leaves unchanged, and it
# fences nomination and Work until its receipt closes it.
res.report["dev_pr_requests"] = []
for cid, c in list(by_id.items()):
if cid in skip:
continue
with isolation.contribution(cid, "development_pr"):
operation = operations.get(c.get("active_operation_id"))
if not operation or operation.get("kind") not in DEVELOPMENT_PR_KINDS \
or operation.get("status") != "planned":
continue
# No row of the table launches a development PR or CI rerun
# operation; its launches are counted like `operation_launch`, on
# the operation.
attempts = recovery.launch_attempts(operation)
waited = (inputs.now - datetime.fromisoformat(operation["updated_at"])).total_seconds() \
>= LAUNCH_INTERVAL_SECONDS
if operation["kind"] == "ci_rerun":
why = _spent_rerun(c, operation, attempts, waited, policy, evidence or {})
if why:
# The rerun failed: it is closed and released, and no row
# is fired. The next observation of interrupted CI takes
# `rerun_interrupted_ci` again within `interrupted_reruns`,
# or `exhaust_interrupted_reruns`.
closed = recovery.fold_failure_receipt(operation, external_ids={}, now=now)
operations[closed["operation_id"]] = closed
released = recovery.release(c, closed, now)
by_id[cid] = released
res.stage("operations", closed)
res.stage("contributions", released)
res.report.setdefault("ci_rerun_closures", []).append(
{"operation_id": closed["operation_id"], "contribution_id": cid,
"closed": why})
continue
due = attempts == 0 or (
waited and attempts < lifecycle.budget_limit("operation_launch", policy))
if due and operation["kind"] == "ci_rerun" \
and engine.state_key(c) == "handoff.waiting_ci":
# CI on the clean head is rerun by the handoff workflow, the
# workflow that writes `riscv64`; `controller.yml`
# dispatches every handoff request.
launched = recovery.charge_launch(operation, now)
operations[launched["operation_id"]] = launched
res.stage("operations", launched)
res.report["handoff_requests"].append({
"operation_id": launched["operation_id"], "contribution_id": cid,
"kind": "ci_rerun", "attempt": attempts + 1})
continue
if due:
launched = recovery.charge_launch(operation, now)
operations[launched["operation_id"]] = launched
res.stage("operations", launched)
res.report["dev_pr_requests"].append({
"operation_id": launched["operation_id"], "contribution_id": cid,
"attempt": attempts + 1,
})
break
for cid, c in list(by_id.items()):
if res.report["dev_pr_requests"]:
break
if len(res.report["dev_pr_requests"]) >= 1:
break
if cid in skip:
continue
with isolation.contribution(cid, "development_pr"):
fork = c.get("fork") or {}
artifact = c.get("proposal_artifact") or {}
pubop = operations.get(c.get("publication_operation_id"))
if engine.state_key(c) != "development.waiting_ci" or c.get("paused") \
or c.get("active_operation_id") or fork.get("pr_number") is not None \
or not fork.get("repository_id") or not fork.get("head_sha") \
or fork.get("head_sha") == c["upstream"].get("base_sha") \
or artifact.get("outcome") != "published" or not artifact.get("result_commit") \
or not c.get("plan_evidence_id") or not c.get("scope_paths") \
or not pubop or pubop.get("status") != "confirmed":
continue
marker = f"<!-- upstreaming-development:{cid}:r{c['revision']}:{fork['head_sha']} -->"
op = recovery.plan(contribution_id=cid, revision=c["revision"], kind="dev_pr_create",
policy_version=policy["policy_version"],
reason_ids=[c["plan_evidence_id"], str(artifact["result_commit"])],
target={"repository": fork["name"], "repository_id": fork["repository_id"],
"ref": DEV_REF, "expected_head": fork["head_sha"],
"base_sha": c["upstream"]["base_sha"]},
proposed={"marker": marker, "content_digest": artifact["digest"]}, now=now)
if op["operation_id"] in operations:
continue
op = recovery.charge_launch(op, now)
res.stage("operations", op)
changed = engine.record_beside(c, "operation_planned", now=now,
active_operation_id=op["operation_id"])
by_id[cid] = changed
res.stage("contributions", changed)
res.report["dev_pr_requests"].append({
"operation_id": op["operation_id"], "contribution_id": cid, "attempt": 1,
})
# Bootstrap CI once for an already recorded PR. This separate operation is
# needed when GitHub registered no inherited workflows at PR creation time.
for cid, c in list(by_id.items()):
if len(res.report["dev_pr_requests"]) >= 1:
break
if cid in skip:
continue
with isolation.contribution(cid, "development_pr"):
fork = c.get("fork") or {}
artifact = c.get("proposal_artifact") or {}
if engine.state_key(c) != "development.waiting_ci" or c.get("paused") \
or c.get("active_operation_id") or fork.get("pr_number") is None \
or c.get("last_ci_evidence_id") or artifact.get("outcome") != "published":
continue
created_at_head = any(op["contribution_id"] == cid and op["kind"] == "dev_pr_create"
and op["status"] == "confirmed"
and op["target"].get("expected_head") == fork.get("head_sha")
for op in operations.values())
if not created_at_head:
continue # later patch pushes already emit pull_request:synchronize
reason = f"ci-bootstrap-event-v2:{fork['head_sha']}"
prior = [op for op in operations.values() if op["contribution_id"] == cid \
and op["kind"] == "dev_pr_update" and reason in op["reason_ids"] \
and op["target"].get("expected_head") == fork.get("head_sha")]
if any(op["status"] in recovery.OPEN | {"confirmed"} for op in prior):
continue
# A re-plan after a failed or never-launched operation is a new
# operation: an operation id is never reused once it closed.
op = recovery.plan(contribution_id=cid, revision=c["revision"], kind="dev_pr_update",
policy_version=policy["policy_version"],
reason_ids=[reason] + ([f"replan:{len(prior)}"] if prior else []),
target={"repository": fork["name"], "repository_id": fork["repository_id"],
"ref": DEV_REF, "expected_head": fork["head_sha"],
"base_sha": c["upstream"]["base_sha"]},
proposed={"marker": f"ci-bootstrap:{cid}:r{c['revision']}",
"content_digest": artifact["digest"]}, now=now)
if op["operation_id"] in operations:
continue
op = recovery.charge_launch(op, now)
res.stage("operations", op)
changed = engine.record_beside(c, "operation_planned", now=now,
active_operation_id=op["operation_id"])
by_id[cid] = changed
res.stage("contributions", changed)
res.report["dev_pr_requests"].append({
"operation_id": op["operation_id"], "contribution_id": cid, "attempt": 1,
})
# 8-10. Select bounded work, honouring capacity and one worker. In a
# state of the table, Work is allocated by the row the table names for
# it, and an exhausted budget takes its exhaustion row instead.
evidence = evidence or {}
candidates = []
for c in by_id.values():
if c["contribution_id"] in skip:
continue
with isolation.contribution(c["contribution_id"], "work_selection"):
if c["contribution_id"] in source_blocked:
continue
kind = _actionable(c)
if kind is None:
continue
if c["contribution_id"] in blocked_by_op:
rep["deferred"].append({"contribution": c["contribution_id"], "why": "uncertain operation"})
continue
if engine.state_key(c) not in lifecycle.LIFECYCLE:
continue # a state the table does not have requests no Work
due = _begun(c, policy, now)
if due is None:
continue
ci = _recorded_ci_evidence(due, evidence)
ops = _open_operations(due, operations)
facts = ALLOCATION_FACTS
if engine.state_key(due) == "handoff.review_pending":
# The review reads the rewritten series from its artifact:
# an expired one is never reviewed, a fresh rewrite is due.
if handoff.rewrite_expired(due, evidence, inputs.now):
out = engine.apply_transition(
due, "expire_submission_rewrite", policy=policy, now=now,
facts={"submission_rewrite_expired"}, open_operations=ops,
cause_id=f"expired-{due.get('submission_rewrite_id')}")
if out.accepted:
by_id[c["contribution_id"]] = out.record
res.stage("contributions", out.record)
res.stage("events", out.event)
continue
else:
facts = ALLOCATION_FACTS | {"submission_rewrite_current"}
spent = next((verb for verb in EXHAUSTIONS.get(engine.state_key(due), ())
if engine.refusal(due, verb, policy=policy, now=now, ci_evidence=ci,
open_operations=ops) is None), None)
if spent:
_exhaust(c, due, spent, ci, by_id, res, policy, now)
continue
verb, why = _allocation_verb(due, ci, ops, policy, now, facts)
if verb is None:
rep["deferred"].append({"contribution": c["contribution_id"], "why": why})
continue
kind = task_for(verb, due)
candidates.append((PRIORITY[kind], c["updated_at"], kind, c, verb))
candidates.sort(key=lambda x: (x[0], x[1]))
# A Result held for a publish-only retry holds no worker.
slots = policy["concurrency"]["coding_workers"] - sum(
1 for c in by_id.values()
if c.get("active_work")
or (c["activity"] == "agent_running" and not c.get("pending_publication")))
pressure = inputs.pressure
for _p, _t, kind, c, verb in candidates:
if c["contribution_id"] in skip:
continue
with isolation.contribution(c["contribution_id"], "work_selection"):
if slots <= 0:
rep["deferred"].append({"contribution": c["contribution_id"], "why": "no worker slot"})
continue
if kind in WRITE_KINDS:
ok, why = capacity.admit_expensive(
pressure or capacity.Pressure(ok=False, reason="no usage data"),