Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 35 additions & 7 deletions nixbot/nixbot/build_reuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from __future__ import annotations

import asyncio
import contextlib
import json
import logging
from typing import TYPE_CHECKING
Expand All @@ -20,35 +19,62 @@
from .db_gen import builds as builds_q
from .db_gen import maintenance as q
from .effects_run import post_effects_summary
from .events import BuildResult, EvalReport
from .events import BuildResult, ChangeEvent, EvalReport
from .gcroots import GcrootRegistrationError
from .gitrepo import GitError, run_git

if TYPE_CHECKING:
from pathlib import Path

from .db import BuildRecord
from .events import ChangeEvent
from .events import RepoInfo
from .gitrepo import FetchCredentials
from .orchestrator import Orchestrator

logger = logging.getLogger(__name__)


async def link_event(o: Orchestrator, event: ChangeEvent, build: BuildRecord) -> None:
"""Link another context to this build, so finish_linked reports to it."""
await builds_q.insert_build_link(
o.pool,
build_id=build.id_,
branch=event.branch,
commit_sha=event.commit_sha,
pr_number=event.pr_number,
tag=event.tag,
actor=event.actor,
)


async def linked_events(
o: Orchestrator, repo: RepoInfo, build: BuildRecord
) -> list[ChangeEvent]:
return [
ChangeEvent(
repo=repo,
branch=row.branch,
commit_sha=row.commit_sha,
pr_number=row.pr_number,
actor=row.actor,
tag=row.tag,
)
for row in await builds_q.build_links(o.pool, build_id=build.id_)
]


async def attach_linked_event(
o: Orchestrator, event: ChangeEvent, build: BuildRecord
) -> None:
"""In-flight (or recovering) build shared with another context:
attach for the final status fan-out."""
o.linked_events.setdefault(build.id_, []).append(event)
await link_event(o, event, build)
await o.reporter.build_started(event, build)
# The build may have turned terminal between the record fetch
# and the attach: the final fan-out already happened and would
# never cover this event. Replay the final status instead.
current = await builds_q.get_build(o.pool, id_=build.id_)
if current is not None and current.status in BuildStatus.TERMINAL:
with contextlib.suppress(KeyError, ValueError):
o.linked_events[build.id_].remove(event)
await replay_terminal_status(o, event, current)
await o.deliver_tag(event, current, current.status)
await deliver_branch_push(o, event, current)
Expand Down Expand Up @@ -93,14 +119,15 @@ async def replay_effect_statuses(

async def finish_linked(
o: Orchestrator,
event: ChangeEvent,
build: BuildRecord,
result: BuildResult,
*,
eval_success: bool | None = None,
) -> None:
"""Final status fan-out for second contexts attached to this
build. eval_success is None when no eval result exists."""
for linked in o.linked_events.pop(build.id_, []):
for linked in await linked_events(o, event.repo, build):
if eval_success is not None:
await o.reporter.eval_finished(
linked, build, EvalReport(success=eval_success)
Expand Down Expand Up @@ -173,6 +200,7 @@ async def reuse_terminal_build( # noqa: PLR0913
# newer build with this old result would cancel it.
return
o.canceller.complete(build.id_)
await link_event(o, event, build)
if build.status == BuildStatus.SUCCEEDED:
try:
await _post_process_existing(o, event, build)
Expand Down
2 changes: 2 additions & 0 deletions nixbot/nixbot/build_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ async def _settle_aborted(
event, build, BuildResult(status, build.status_generation, [])
)
await o.finish_linked(
event,
build,
BuildResult(status, build.status_generation, []),
eval_success=None if status == BuildStatus.CANCELLED else False,
Expand Down Expand Up @@ -610,6 +611,7 @@ async def record_early(result: AttributeResult) -> None:
),
)
await o.finish_linked(
event,
build,
BuildResult(status, generation, schedule_result.results),
eval_success=True,
Expand Down
34 changes: 34 additions & 0 deletions nixbot/nixbot/db_gen/builds.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

__all__: collections.abc.Sequence[str] = (
"AttributeStatusesRow",
"BuildLinksRow",
"EffectDepStatusesRow",
"EffectsSummaryRow",
"EvalJobRowsRow",
Expand All @@ -17,6 +18,7 @@
"attribute_status_list",
"attribute_statuses",
"backfill_pr_author",
"build_links",
"bump_build_status",
"claim_effect",
"clear_effect_eval_error",
Expand All @@ -35,6 +37,7 @@
"finish_effect",
"get_build",
"insert_build_effects",
"insert_build_link",
"last_real_run_with_inputs",
"lock_build_identity",
"lock_build_row",
Expand Down Expand Up @@ -74,6 +77,15 @@ class EvalJobRowsRow:
outputs: str | None


@dataclasses.dataclass()
class BuildLinksRow:
branch: str
commit_sha: str
pr_number: int | None
tag: str | None
actor: str | None


@dataclasses.dataclass()
class EffectDepStatusesRow:
name: str
Expand Down Expand Up @@ -238,6 +250,17 @@ class LastRealRunWithInputsRow:
SELECT id, project_id, number, tree_hash, commit_sha, branch, pr_number, pr_author, status, status_generation, effects_started, error, created_at, started_at, finished_at, eval_warnings, eval_completed, effects_commit_sha, effects_branch, effects_pr_number, eval_duration_ms, actor, merged_pr_number FROM builds WHERE id = $1
"""

INSERT_BUILD_LINK: typing.Final[str] = """-- name: InsertBuildLink :exec
INSERT INTO build_links (build_id, branch, commit_sha, pr_number, tag, actor)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT DO NOTHING
"""

BUILD_LINKS: typing.Final[str] = """-- name: BuildLinks :many
SELECT branch, commit_sha, pr_number, tag, actor FROM build_links
WHERE build_id = $1 ORDER BY id
"""

RECORD_EFFECTS_REF: typing.Final[str] = """-- name: RecordEffectsRef :exec
UPDATE builds SET
effects_commit_sha = $1::text,
Expand Down Expand Up @@ -740,6 +763,17 @@ async def get_build(conn: ConnectionLike, *, id_: int) -> models.Build | None:
)


async def insert_build_link(conn: ConnectionLike, *, build_id: int, branch: str, commit_sha: str, pr_number: int | None, tag: str | None, actor: str | None) -> None:
await conn.execute(INSERT_BUILD_LINK, build_id, branch, commit_sha, pr_number, tag, actor)


def build_links(conn: ConnectionLike, *, build_id: int) -> QueryResults[BuildLinksRow]:
def _decode_hook(row: asyncpg.Record) -> BuildLinksRow:
return BuildLinksRow(branch=row[0], commit_sha=row[1], pr_number=row[2], tag=row[3], actor=row[4])

return QueryResults(conn, BUILD_LINKS, _decode_hook, build_id)


async def record_effects_ref(conn: ConnectionLike, *, commit_sha: str, branch: str, pr_number: int | None, id_: int, allowed: bool) -> None:
await conn.execute(RECORD_EFFECTS_REF, commit_sha, branch, pr_number, id_, allowed)

Expand Down
14 changes: 14 additions & 0 deletions nixbot/nixbot/migrations/0039_build_links.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- Commits that reused a build of the same tree. A restart reports to
-- these as well as to the build's own commit
CREATE TABLE build_links (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
build_id BIGINT NOT NULL REFERENCES builds (id) ON DELETE CASCADE,
branch TEXT NOT NULL,
commit_sha TEXT NOT NULL,
pr_number BIGINT,
tag TEXT,
actor TEXT
);
CREATE UNIQUE INDEX build_links_context_idx ON build_links (
build_id, commit_sha, branch, COALESCE(pr_number, 0), COALESCE(tag, '')
);
19 changes: 15 additions & 4 deletions nixbot/nixbot/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
NullStatusReporter,
RepoInfo,
StatusReporter,
event_for_build,
)
from .executor import (
LogWriter,
Expand Down Expand Up @@ -161,8 +162,6 @@ class Orchestrator:
log_registry: LogRegistry = field(default_factory=LogRegistry)
# Per-run bearer tokens for the hercules state API.
task_tokens: TaskTokens = field(default_factory=TaskTokens)
# Second contexts attached to an in-flight build, for status fan-out.
linked_events: dict[int, list[ChangeEvent]] = field(default_factory=dict)
# Caps concurrent evaluations to bound memory use.
eval_slots: asyncio.Semaphore = field(init=False)
# Pulsed on every release_run().
Expand Down Expand Up @@ -418,7 +417,6 @@ async def _dispatch_build( # noqa: PLR0913
finally:
self.canceller.complete(build.id_)
self.release_run(build.id_)
self.linked_events.pop(build.id_, None)

async def run_build(
self,
Expand Down Expand Up @@ -602,14 +600,27 @@ async def open_effect_log(self, run_id: int) -> AsyncIterator[LogWriter]:

async def finish_linked(
self,
event: ChangeEvent,
build: BuildRecord,
result: BuildResult,
*,
eval_success: bool | None = None,
) -> None:
"""Final status fan-out for second contexts attached to this
build. eval_success is None when no eval result exists."""
await build_reuse.finish_linked(self, build, result, eval_success=eval_success)
await build_reuse.finish_linked(
self, event, build, result, eval_success=eval_success
)

async def build_restarted(
self, info: RepoInfo, build: BuildRecord, attr: str | None
) -> None:
"""Mark the build and every context linked to it pending."""
for event in [
event_for_build(info, build),
*await build_reuse.linked_events(self, info, build),
]:
await self.reporter.build_restarted(event, build, attr)

async def post_process_skipped(
self, event: ChangeEvent, skipped: list[tuple[str, str]]
Expand Down
9 changes: 9 additions & 0 deletions nixbot/nixbot/queries/builds.sql
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,15 @@ WHERE build_id = $1;
-- name: GetBuild :one
SELECT * FROM builds WHERE id = $1;

-- name: InsertBuildLink :exec
INSERT INTO build_links (build_id, branch, commit_sha, pr_number, tag, actor)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT DO NOTHING;

-- name: BuildLinks :many
SELECT branch, commit_sha, pr_number, tag, actor FROM build_links
WHERE build_id = $1 ORDER BY id;

-- name: RecordEffectsRef :exec
-- The ref maybe_run_effects last decided for. Effect items (which only
-- carry build_id) report on it, and restarts gate on it instead of the
Expand Down
9 changes: 4 additions & 5 deletions nixbot/nixbot/restart_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
ChangeEvent,
EvalReport,
effects_event_for_build,
event_for_build,
)
from .recovery import check_store_paths, find_unfinished_builds
from .repos import repo_info
Expand Down Expand Up @@ -93,7 +92,7 @@ async def rerun(
build = await builds_q.get_build(o.pool, id_=build_id)
if build is None:
return
await o.reporter.build_restarted(event_for_build(info, build), build, attr)
await o.build_restarted(info, build, attr)
results = await find_unfinished_builds(s.pool, build_id=build_id)
resumable = results[0] if results else None
if resumable is None:
Expand Down Expand Up @@ -188,7 +187,7 @@ async def _report_interrupted(s: CIService, resumable: ResumableBuild) -> None:
event = await change_event_for(s, resumable)
if build is None or event is None:
return
result = BuildResult(BuildStatus.FAILED, build.status_generation, [])
await s.orchestrator.reporter.eval_finished(event, build, EvalReport(success=False))
await s.orchestrator.reporter.build_finished(
event, build, BuildResult(BuildStatus.FAILED, build.status_generation, [])
)
await s.orchestrator.reporter.build_finished(event, build, result)
await s.orchestrator.finish_linked(event, build, result, eval_success=False)
41 changes: 41 additions & 0 deletions nixbot/nixbot/tests/test_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2492,6 +2492,47 @@ async def test_restart_build_drops_queued_effect_items(
assert await effect_statuses(pool, build.id_) == {}


async def test_restart_reports_to_commits_that_reused_the_build(
pool: asyncpg.Pool,
make_env: EnvFactory,
upstream: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
add_commit(upstream, "restart-linked")
sha1 = git(upstream, "rev-parse", "HEAD")
executor = FakeExecutor(outcomes={"a": BuildOutcome.failure})
orchestrator, reporter, project = await make_env(
FakeEvalRunner([mk_job("a")]), executor, name="restart-linked"
)
finished: list[tuple[str, str]] = []

async def build_finished(
event: ChangeEvent, build: BuildRecord, result: BuildResult
) -> None:
finished.append((event.commit_sha, result.status))

monkeypatch.setattr(reporter, "build_finished", build_finished)

build = await orchestrator.handle_change_event(
ChangeEvent(repo=project, branch="main", commit_sha=sha1, pr_number=7)
)
git(upstream, "commit", "--allow-empty", "-m", "rerun ci")
sha2 = git(upstream, "rev-parse", "HEAD")
reused = await orchestrator.handle_change_event(
ChangeEvent(repo=project, branch="main", commit_sha=sha2, pr_number=7)
)
assert build is not None
assert reused is not None
assert reused.id_ == build.id_

executor.outcomes.clear()
await orchestrator.reset_build_for_restart(build.id_, None)
build = await builds_q.get_build(pool, id_=build.id_)
assert build is not None
await orchestrator.rerun_pending_attributes(project, build, [mk_job("a")])
assert finished[-1] == (sha2, BuildStatus.SUCCEEDED)


async def test_restart_effects_after_pr_attach_keeps_effects_ref(
pool: asyncpg.Pool,
make_env: EnvFactory,
Expand Down
Loading