Compare commits

..
191 Commits
Author SHA1 Message Date
mesh-tools 3f1e4aea03 Merge pull request 'Pipeline runner: the test-run test waits on what it causes, never on a clock across a restart (issue 1984)' (#363) from fix/1984-testruns-flake into main 2026-11-24 01:36:59 +00:00
jschoubben b71bc6fbaf Runner: the test-run test waits on what it causes, never on a clock across a restart (issue 1984)
Test 109 (TestTestRunsAreAskedOncePerLevelAndMoveEveryReader) failed on a loaded build node and passed on the same
commit when it ran again. Test-only; no behaviour of the runner changes.

- The first start has a step bound of a minute, longer than the restart; the setting is rewritten to two seconds between
  stop() and start(), so the clock the first runner armed at the take cannot end the run before the restarted runner
  hears the first progress.
- start() waits for one more "take-ins: heard on the consumer" line than before it (takeInsHeardMore), where it matched
  the first start's line still in the shared buffer.
- An ask is read from the stream, and said taken, only once it is on the stream (askPut, waited for with waitFor): the run
  names its ask before the runner has written the ask key and put the ask, so the one read of the stream failed with
  "message not found", and an ask-taken heard before the ask key is written moves nothing (read at the silent-bound
  wait: the ask key was absent when the take was said), so the clock of the ask never began and the wait ran 60 s.
- The progress wait stops at once, naming the run, when the run has ended.

Builds: design 47 H2 H-A-637
2026-11-24 02:17:55 +01:00
mesh-tools b810407f50 Merge pull request 'Assigner: a pass past pass-stall-seconds says which phase it is in (issue 1984)' (#362) from fix/1984-pass-stall into main 2026-11-24 00:30:31 +00:00
jschoubben 3bc30b7284 assigner: label the pass-stall rows with acceptance 1984/AC13 (issue 1984, review round 1)
The subtest of the pass-stall rows in TestAPassWritesWantsWhileAKeepingIsBlocked
carries the label 1984/AC13 beside the design line it checks.

Builds: design 47 H2 H-A-635 (1984/AC13)
2026-11-24 01:28:54 +01:00
jschoubben 377a0c27db assigner: a pass past pass-stall-seconds says which phase it is in (issue 1984)
The assigner's pass names the phase it is in as each starts (the assignments
seat, the kept graph, the wants, the pass said, the puts, the node wants, the
backups and reverts), in the passer's own memory. A pass still running after
the new setting pass-stall-seconds (10 to 600, default 60, read from its file
as package-wait-minutes is) says once in the journal "the pass started at
<time> is in <phase> for <duration>", and again at each further bound until it
ends; a pass that ends within the bound says none, and the end line "the pass
took" stays as H-A-259 has it. A stall met 2026-11-23 left the journal silent
for six minutes with no way to tell where the pass stood.

Builds: design 47 H2 H-A-635 (on H-A-259)
2026-11-24 01:15:43 +01:00
mesh-tools 7b1756e59c Merge pull request 'Indexer and assigner: a take-in blanks only a mover's entry; a run's empty pin is filled from mesh-builds.published or waited for (issue 1984)' (#361) from fix/1984-empty-pin into main 2026-11-23 22:37:58 +00:00
jschoubben 773ba91222 assigner: at the put of a run that waited for a package its readers wait for a build node again (issue 1984, review round 1)
Once a run's wait for a package's publish ended and its run ask was put,
`waits` was deleted but its readers' newest wait-held still said they
waited for the package's publish, until ask-taken's wait-ended. Now the
start that deletes `waits` as it writes the run's program says its
readers' wait-held for a build node again, under their held id with
.put added, so the bus's duplicate window keeps it apart from the first;
the composition and the validate run alike.

Tests: TestTheCompositionStepRunsOneAskPerMachine, the wait's rows: after
the put each machine's newest wait-held is for a build node under its
held id with .put; TestTheValidateStepRefusesAManifestProblemAndACycle,
revision 14: the reader is said waiting for mesh-sdk's publish, then for
a build node again at the put. Both failed first without the say at the
put.

Builds: design 47 H2 H-A-632 (hq c7f31726, f9be4ef0); H-A-630 (5) (hq 1cdfa6ff); H-A-629 (1), (2) (hq 8aa70271)
2026-11-23 23:19:56 +01:00
jschoubben 5884f8ed7b assigner: while a run waits for a package's publish its readers' wait-held names that package (issue 1984, review round 1)
A run waiting for a package's publish left its readers said waiting for
a build node (`on: build node`), though no ask was put. While the run's
value holds `waits`, waitOf now says the step waits for the publish of
that package (`on: publish of package <path>`, since the wait began),
naming the package and the entry, never a build node; the readers are
said so when the wait begins, under their held id with the package's
path added, so the bus's duplicate window keeps it apart from the first,
and a reader joining a waiting run is said so at its join.

Test: TestTheCompositionStepRunsOneAskPerMachine, the wait's rows: each
reader's wait-held names the publish of x/go and the node-engine's entry
(failed first, no such wait-held within 10 s, with waitOf ignoring
`waits`).

Builds: design 47 H2 H-A-630 (5) (hq 1cdfa6ff); H-A-631 (hq ee89b857); A-469y
2026-11-23 23:17:41 +01:00
jschoubben a46f14ba23 assigner: the words past a wait's bound name the package, the entry and the bound (issue 1984, review round 1)
A run past its wait's bound ended "package <path> has no published
version within <bound>", naming no entry, and two of its three paths
(the bound's expiry and the take-up at a start) read only the run's
value. The seat mesh-wants' CompositionRunWaits gains `entry`, the words
of the import-form entry the run is built from (such as "the
node-engine's entry src2:e1"), written with the package when the wait
begins; the waiting start's end, the expiry and the take-up all say
"package <path> has no published version within <bound>
(package-wait-minutes), named with no version in <entry>" from it. The
definition's form stays 3, raised by this fix; the Go and TypeScript
contracts regenerated by seatgen (seatgen -check passes).

Tests: TestTheCompositionStepRunsOneAskPerMachine, the wait's rows: the
waiting run's `waits` holds its entry; "past its bound" (the expiry) and
a new "past its bound at a take-up" (takeUpWaits) end saying package,
entry and bound (both failed first with no entry written);
TestTheCompositionStepComposesEachMachineThroughTheBuildSeat (whole,
embedded bus): the waiting run's entry, and the take-up's and the
expiry's words with it.

Builds: design 47 H2 H-A-630 (4) (hq 1cdfa6ff); H-A-631 (hq ee89b857); H-A-628 (3), (5) (hq cea6404c); H-A-629 (1) (hq 8aa70271); H2 §780
2026-11-23 23:14:57 +01:00
jschoubben dc2ddb871a assigner: a run's start and its wait run on the assigner's own context (issue 1984, review round 1)
The composition and validate runs were started on the context of the
step that started them, so a supersede or a drop of that step ended the
wait for a package's publish silently, while other steps share the run:
it then waited, woken by nothing, until its bound ended it "no published
version" though the package stood published. The start, its wait and
its run ask now run on the assigner's own context (compositionRun.own),
as the take-up's do.

Tests: TestTheCompositionStepRunsOneAskPerMachine, the wait's rows gain
"superseded": a second step joins the waiting runs, the starting step's
context ends, the runs stay waiting with both readers, and at the
publish the second step reads them composed with the pin;
TestTheValidateStepRefusesAManifestProblemAndACycle, revision 14: the
validate run waiting for mesh-sdk's publish outlives its starting step
and ends passed after the publish. Both failed first (no end within
10 s) with the start on the step's context.

Builds: design 47 H2 H-A-630 (3) (hq 1cdfa6ff); H-A-628 (3) (hq cea6404c); H-A-629 (3) (hq 8aa70271)
2026-11-23 23:11:32 +01:00
jschoubben 051e104f1b assigner: each bind of the package-published consumer wakes every waiting run (issue 1984, review round 1)
The bind wake stood in main.go untested. It now sits beside the
consumer's handler in hearPublished, which registers both: each bind of
the assigner's consumer of package-published wakes every run waiting for
a package's publish to read published again, since an event said while
the consumer was not bound is never heard.

Test: TestTheCompositionStepRunsOneAskPerMachine, the wait's rows gain
"bind": x/go published with no event heard, a bind of the consumer wakes
each waiting run, which reads it published and puts its run ask with the
pin (failed first, no end within 10 s, with the bind's hearer removed).

Builds: design 47 H2 H-A-630 (2) (hq 1cdfa6ff); H-A-628 (3) (hq cea6404c)
2026-11-23 23:06:56 +01:00
jschoubben 8a1605d283 assigner: a package-published wakes only the runs waiting for its artifact's package (issue 1984, review round 1)
Every package-published heard woke every run waiting for any package,
each asking mesh-builds' published again. Now the wake is kept per the
artifact of a package's publisher: the assigner's consumer reads the
heard event's artifact (hearPublished) and wakes only the runs whose
`waits` names the package that artifact publishes, as the runner's
hearPublished matches by artifact; a publish of another package wakes
none and asks no published. An event that does not read is journaled
and wakes none. Each bind of the consumer still wakes every waiting run
(heardBind).

Test: TestTheCompositionStepRunsOneAskPerMachine, the wait's row: a
package-published of y:go, handed to the consumer's handler while the
runs wait for x/go, leaves their wake standing and asks no published;
x:go's own then wakes them (failed first with the wake ignoring the
artifact).

Builds: design 47 H2 H-A-630 (1) (hq 1cdfa6ff); H-A-628 (3) (hq cea6404c); H-A-326
2026-11-23 23:05:51 +01:00
jschoubben 4bcc12d7b1 T3 assigner: a run waits for its package's publish, bounded, then could not run naming it (issue 1984)
T2 ended a composition or validate run at once when its entry named a
package whose publisher's build in the step's revision was not published
yet. Now the run waits: it reads mesh-builds' published first and again
at each package-published heard (and at each bind of the consumer); the
run's value names the package and the time its wait began in `waits`;
its bound bound.<run key> is armed for what is left of the new setting
package-wait-minutes (1 to 120, default 10). Past the bound the run ends
could not run, "package <path> has no published version within <bound>
(package-wait-minutes)", never the builder's words. `waits` and the
bound go when the run ask is put (an ask in the queue has no clock) or
the run ends. Every step reading the run says the phase fetch while it
holds `waits`, its journal naming the package, and run once none does.
At the assigner's start a run holding `waits` and no program ends past
its bound, or has its bound armed again for what is left and its whole
start run again. A run with no publisher still ends at once (principle 3).

The seat mesh-wants' CompositionRun gains `waits` {package, since}, its
form raised to 3 as a field added (§780, H-A-352 (3)); the Go and
TypeScript contracts regenerated by seatgen. The assigner consumes
mesh-builds.package-published.

Tests: TestTheCompositionStepRunsOneAskPerMachine (rows: the wait, its
`waits` and bound, the phase fetch then run, the pin after the publish
with `waits` and the bound gone at the put, past the bound) for 1984/AC9;
TestACompositionRunIsOneKeyPerCandidateAndMachine/settings;
TestManifest; TestTheCompositionStepComposesEachMachineThroughTheBuildSeat
extended (the wait and the publish event, a restart during the wait,
a run past its bound at the restart and one past it while running) for
1984/AC11.

Builds: design 47 H2 H-A-628 (3), (4), (5) (hq 8aa70271); H-A-629 (1), (2), (3) (hq 8aa70271); D4 H-A-192; D9 H-A-326, H-A-328; G §719, §720; H2 §780 with H-A-352 (3)
2026-11-23 22:35:43 +01:00
jschoubben 024c137b94 T2 assigner: an empty pin of a run's entry is filled from mesh-builds.published (issue 1984)
The composer's and the validator's run asks go straight to the Go build
seat, never through the builder, and pinsOfEntry dropped a pin the entry
names with no version, so the build module refused at once with words
that blame the builder. Now each empty pin is filled by asking the seat
mesh-builds' verb published of the package's publisher in the step's
catalog revision; the version it answers is the pin. No run ask is put
with a pin left out: a build not yet published, or a package no build of
the revision publishes, ends the run could not run naming the package and
the entry (the wait for the publish comes with T3).

The assigner requires the meshbuilds contract module and its manifest
invokes seat:mesh-builds.published (TestManifest holds it).

Tests: TestTheCompositionStepRunsOneAskPerMachine (its stand's revision
holds x's publisher; rows "not published" and "no publisher") for
1984/AC9; TestTheValidateStepRefusesAManifestProblemAndACycle, revision
13, for 1984/AC10.

Builds: design 47 H2 H-A-628 (2), (5) (hq cea6404c); D4 H-A-192; D5 H-A-204; D7 G §718, A-252, A-451; D8 H §745; D9 H-A-326, H-A-328
2026-11-23 22:00:31 +01:00
jschoubben b7b3891a4a T1 indexer: blank only a mover's entry (issue 1984)
The take-in blanked a package's pin in every import-form entry, the
node-engine's among them though it was no mover, and nothing filled it:
every composition of main.506 could not run. A module that is no mover
of the take-in keeps its pins, since no step of that pipeline builds it.

Tests: TestMoversOf gains the subcase "an import-form importer that is no
mover keeps its pin of a package a mover publishes" (1984/AC7); I12's
subcase is kept as 1984/AC8. TestASourceRevisionMovingMeshSDKNamesItAndItsImporters
(integration) asserted the old blank for importer at m3's take-in, where
the take-in makes importer no mover (its fingerprint does not move,
noted on issue 1984 as note 24); its assertion now follows H-A-628 (1):
blank where importer is a mover of that take-in, its pin kept where not.

Builds: design 47 H2 H-A-628 (1) (hq cea6404c); D1 H-A-532 DMC-1; D2 H-A-547 (2)
2026-11-23 21:55:02 +01:00
mesh-tools b1493ede79 Merge pull request 'Builder: a reservation's kept publishes are taken in before its bound is judged; version-unreleased only for a version left unpublished, never over a finding that stands (issue 1984)' (#360) from fix/builder-record-digests into main 2026-11-23 18:34:53 +00:00
jschoubben ee80b0be47 mesh-delivery-builder: a bound's end raises nothing for a reservation whose every artifact is published (issue 1984, review round 2)
The bound's end (ended) raised version-unreleased for a built reservation
whose every artifact was published, saying "an artifact is unpublished",
while arm past the bound leaves that reservation waiting for its
version-released. 1984/AC5 raises only for a built reservation left unmarked
past its bound, so ended now raises nothing when no artifact is missing.

Builds: issue 1984 note 8 (1984/AC5), design 47 G §369
2026-11-23 18:47:14 +01:00
jschoubben 83f858df7a mesh-delivery-builder: judge a built reservation's bound after its kept published are taken in; only a raise with words of its own writes over a standing version-unreleased (issue 1984, review round 2)
A built reservation's bound was judged before the published kept on it were
taken in, at a look (Built) and at the start: one past its bound whose kept
published mark every artifact (note 8's own case) raised version-unreleased
naming every artifact unpublished, then said package-published for each, and
the false finding stood until its version-released. The kept are now taken in
first (Kept answers the reservation as its take-in left it), and the bound is
armed or judged on that reservation.

The bound's end (ended) raised "nothing within" over the words the publish
again left within the bound, the kind round 1 fixed past the bound. Every raise
that says only the bound ended or could not be armed now goes through lapsed,
which raises only when no version-unreleased of the module stands (Held,
design 47 G A-38). The raises with words of their own, a holder's refusal of a
publish again (ADR 0674 §3: left "raised with the holder's words") and a digest
no artifact carries (A-490j: "fails loudly"), still write over a standing one.

Builds: issue 1984 note 8 (1984/AC5), design 47 G §369, A-415, A-38, A-490j, ADR 0674 §3
2026-11-23 18:43:45 +01:00
jschoubben 8e600d3a52 Merge mesh-delivery main a118976b into fix/builder-record-digests (issue 1984) 2026-11-23 18:40:24 +01:00
mesh-tools a118976bc0 Merge pull request 'Pipeline runner: a step's end ends only its step, read from the bus; a bound re-arms only while step ends still drain (issue 1984)' (#359) from fix/runner-step-ends into main 2026-11-23 17:25:36 +00:00
jschoubben 828f905694 mesh-delivery-builder: a standing version-unreleased keeps its words past the bound (issue 1984, review round 1)
The past-bound branch of arm is reached at every look, and raised
version-unreleased again each time as "nothing within 10m0s of its build",
writing over the words it was left with (a holder's refusal, ADR 0674 §3;
design 47 G A-490j). Once the bound has passed it now raises only when the
held writer holds no version-unreleased of the module (Held, design 47 G
A-38).

Builds: issue 1984 note 8 (1984/AC5), design 47 G §369, A-38, A-490j
2026-11-23 18:22:21 +01:00
jschoubben d0a04b77f0 mesh-delivery-builder: record a build's digests in one write and take a built reservation in from its state (issue 1984)
mesh-delivery-contracts 0.1.108's 39 digests were recorded one artifact at a
time, each a rewrite and a reindex (about 850 index reads), and timed out three
times under the one-minute record bound after its build was ended: its bound was
never armed, the published kept on it never taken in, and RecordAgain skipped it
since its build stood ended, so nothing said it (main.495's tier 2 held).

- versions.Reserver.Built takes the whole digest map: one compare-and-set of the
  reservation and one reindex; an artifact recorded already is skipped, so a
  record tried again writes only what the one before left, and nothing when all
  stand (1984/AC4). It answers the reservation as written, so the holder no
  longer reads every reservation after the record.
- What follows a record follows the reservation's state: RecordAgain hands a
  recorded reservation to Built at every look, and the start takes in every
  built one not released: its bound is armed, counted from its build's end, and
  the published kept on it are taken in and said as package-published; one left
  with an artifact unpublished past its bound raises version-unreleased at once
  and is not armed again (1984/AC5).

Builds: issue 1984 note 8 (1984/AC4, AC5), design 47 G §369, A-415, A-456b, A-457a, H-A-492
2026-11-23 18:22:14 +01:00
jschoubben e9673046cb Runner: read the bus, not a copy; arm a bound only while its count shrinks (issue 1984)
Review round 1. The store kept a running pipeline's mover-key values in
memory while its record stayed at the revision read, but the module's
own runner_unlogged_append writes through a store of its own: a read
between that store's record write and its mover-key writes kept old
values at the new revision, and the runner served `running` while the
bus held `passed`. The copy goes; each key is still read by its name,
none listed, with the trunk's check of the revisions read.

A bound passing while step ends wait now arms the bound again only while
their count (not yet delivered plus unacknowledged) shrank since the
bound before, kept as `waited` on the ask's mark beside `unread`: an end
the handler naks forever, which no delivery limit stops, ends the step
saying the count did not shrink. Every such why says only what is true
("its ask X is not known to be answered: ..."), and none raises
call-unanswered. The ask clock the start makes now reads the durable
itself, so the integration row fails when the start wires none; the
nudge's mutex is the hearer's own.

Builds: issue 1984 note 6 (1984/AC1, 1984/AC2), notes 7 (b), (c), 9 (d), 10 (e)
2026-11-23 18:07:56 +01:00
jschoubben 1a8b7c8591 Runner: a bound passing while step ends wait arms it again (issue 1984)
An ask's bound ended its step "not answered: its holder said nothing"
while the holder's end waited, untaken, in the runner's own step-ended
durable: the runner's queue was counted against the holder (issue 1984,
note 6). As a bound passes the runner now reads that durable once, its
consumer's not-yet-delivered and unacknowledged step ends: while any
wait, the step is not ended, its bound is armed again whole and the
journal says how many wait; with none waiting the step ends with the
why it had, the journal naming the count read. A read that fails arms
the bound once more, kept as `unread` on the ask's own mark in test-runs,
cleared by a read that succeeds; a second failed read in a row ends the
step saying the runner could not read its durable, and raises no
call-unanswered, whose words say the holder said nothing.

Builds: issue 1984 note 6 (1984/AC2), note 7 (a), (b), (c)
2026-11-23 18:02:01 +01:00
jschoubben 3fc9e194b9 Runner: a step's end only ends its step; the store lists no key (issue 1984)
The runner took the step ends one at a time at about 13 s each, because
each handler aged up to twenty step-log entries and checked the stores'
fill, and every read and write of a pipeline listed its mover keys
through a new consumer (issue 1984, note 6). The ageing and the fill
check now run as work of their own, nudged by the step ends: the ends
heard while a pass runs merge into one pass after it, and never two run
at once. The pipelines store reads each key by its name and keeps a
running pipeline's mover keys from its last read or write while the
record is still at that revision (every write of a mover key writes the
record too), so a step's end reads the record and writes the record and
its own mover key; a store after a restart, or a pipeline not running,
reads the keys its record names, never a listing.

Builds: issue 1984 note 6 (1984/AC1), ADR 0682 §11
2026-11-23 18:02:01 +01:00
mesh-tools 8bbe956102 Merge pull request 'mesh-delivery-builder: format step_test.go as gofmt writes it (issue 721)' (#358) from fix/builder-gofmt into main 2026-11-23 16:26:35 +00:00
jschoubben 6715389a88 mesh-delivery-builder: format step_test.go as gofmt writes it (issue 721; main.495's lint failed on it) 2026-11-23 17:26:06 +01:00
mesh-tools 349fbc3a08 Merge pull request 'The pipeline runner reads its step log by sequence, opening no consumer (design 47 G §330; issue 1982)' (#357) from fix/steplog-read into main 2026-11-23 13:00:19 +00:00
jschoubben 0f7d9290e0 Read the step log by sequence, with no consumer per read
The runner's ageing read the step log through a new ordered consumer at
every retention of every step's end and never removed it: 604 consumers
in 11 minutes, each starting tens of thousands of entries back, ran the
bus at 196% CPU (issue 1982, note 16). The log is now read entry by
entry with the stream's own message get (next entry of the log's
subjects at or after the sequence, so deleted ones are passed over),
and each retention reads its oldest unaged entry alone first: while it
is not past the retention nothing after it is, so a step's end reads
one entry per retention, not twenty.

Builds: design 47 G §330
2026-11-23 13:57:47 +01:00
mesh-tools b79092cf97 Merge pull request 'Import fingerprint: a module moves only when a package it imports changes (issue 721, design 47 H2)' (#356) from fix/fp-imports into main 2026-11-23 12:22:42 +00:00
jschoubben d6e56d98f9 Merge remote-tracking branch 'origin/main' into fix/fp-imports 2026-11-23 13:19:00 +01:00
jschoubben e5a250d774 I6: a take-in moves another repository's importer by its import set, in either language
Review r1 finding 1: a module of another repository was recomputed only when
a pin's Go module path mapped to the moved repository, so a TypeScript
importer of @novox/mesh-sdk never moved on a mesh-sdk take-in. It now moves
when its reported import set holds a package the moved repository publishes
(the module graph's entries), or, with no set, when a pin names one.

Builds: design 47 H2 H-A-520, H-A-523, H-A-528, H-A-539
2026-11-23 13:17:15 +01:00
jschoubben 3945640247 I12: the indexer's whole test proves a take-in's revision names a moved package with no version
Review r1 finding 2: removing the take-in's unpinnedByMovers failed no test.
I10 now takes mesh-sdk in again after its releases and reads the take-in's
revision: the import-form importer names mesh-sdk with no version, legacy
(the version line) keeps its pin.

Builds: design 47 H2 H-A-532 (DMC-1), H-A-547 (2), H-A-521
2026-11-23 13:15:17 +01:00
jschoubben e25aed10bb B4: the bed watches the reserved bucket for the release's delete, never polls
Review r1 finding 3: the wait for the reservation's delete slept between
reads; it now watches the module's keys and ends on their delete.

Builds: design 47 H2 H-A-551
2026-11-23 13:14:17 +01:00
jschoubben a82e97baf4 B4: the builder's bed proves an unpinned package filled at the key's origin
An entry naming a mesh package with no version is built, in the builder's
bed, with the version its publisher reserved at the source revision of the
key's own origin once a registry seat says that version published, not the
newer one another published said; and, once that version is released and its
reservation gone, the next such build takes it from the release record. A
case of the existing done-key test, so the integration count stays at 17.

Builds: design 47 H2 H-A-521, H-A-547 (3), H-A-551, H-A-558 (2)
2026-11-23 13:03:01 +01:00
mesh-tools 6ce2e0a652 Merge pull request 'A build is superseded only by a newer revision's entry (design 47 H2, H-A-555, H-A-557, H-A-561..H-A-563)' (#355) from fix/supersede-newer into main 2026-11-23 11:51:25 +00:00
jschoubben 71648fbe9e mesh-delivery-pipeline: the pipeline's own revision moves the mover out; a revision wait is said (H-A-563)
Only a superseded end naming a revision older than the pipeline's is
asked again; one naming the pipeline's own revision (the builder's
kept-revision path) moves the mover out as H-A-508 has it, so no re-ask
can loop. A build that starts waiting on the revision view says
wait-held, on: revision view, and wait-ended when the view's move ends
it, as the operator's wait does.

Builds: design 47 H2 H-A-563
2026-11-23 12:50:08 +01:00
jschoubben fb3f186aed mesh-delivery-pipeline: judge a superseded build by the revision its end names (H-A-561, H-A-562)
A build ended superseded is judged by the module graph revision its end
names of the entry that superseded it, never by the order entries were
heard in: none (a builder before H-A-561) moves the mover out as before;
one not newer than the pipeline's own is asked again at once; one newer
the runner's view does not hold yet keeps the step waiting on the
revision view, its revision in the pipeline's value, and each move of
the view judges such steps again, moving the mover out once it holds
the revision; one newer and held moves the mover out at once. No re-ask
can loop: the builder names the revision it judged by.

Builds: design 47 H2 H-A-555, H-A-561, H-A-562
2026-11-23 12:44:19 +01:00
jschoubben f9e2bbe193 mesh-delivery-builder: a superseded end names the superseding entry's revision (H-A-561)
A build step ended superseded names the module graph revision of the
entry that superseded it: the revision the picture heard that entry at,
or the ask's own revision where the catalog's kept revision names the
newer fingerprint. The runner then judges the end by that revision, not
by the order the entries were heard in.

Builds: design 47 H2 H-A-561
2026-11-23 12:39:18 +01:00
jschoubben 68a629d380 Seats mesh-builds and mesh-pipeline-runner: a superseded end names its revision, a held step keeps it (H-A-561, H-A-562)
The seat mesh-builds' step-ended gains revision: for a step ended
superseded, the module graph revision of the entry that superseded it,
so the runner judges it without the order entries are heard in (form 3).
The seat mesh-pipeline-runner's step gains revision: for a step waiting
on the revision view, the revision it waits for, kept in the pipeline's
value (form 12). Regenerated, with a fixture of each.

Builds: design 47 H2 H-A-561, H-A-562
2026-11-23 12:37:57 +01:00
jschoubben e247ccc794 mesh-delivery-builder: an older revision's entry stays behind the newest heard (H-A-557, review r1)
An entry heard of an older module graph revision than the one the
picture holds for its branch neither replaces it as the newest nor
withdraws its build; it is said in the journal. The test hears revision
453's entry with its build running, then 452's, then 454's.

Builds: design 47 H2 H-A-557
2026-11-23 12:35:19 +01:00
jschoubben 9a705d69b5 Merge remote-tracking branch 'origin/main' into fix/fp-imports 2026-11-23 12:33:10 +01:00
jschoubben 0689f69ea7 I13b: the fill's call-unanswered of builder_versions is retired
The versions fill went, so nothing raises or clears its
indexer-call-unanswered of builder_versions any more: the indexer's writer
clears that id once at its start, the kind staying raised for its other
calls.

Builds: design 47 H2 H-A-558 (3), H-A-552
2026-11-23 12:33:04 +01:00
jschoubben d1256ec941 B4: the released record keeps the origin's branch with its source revision
Source revisions are numbered per watched branch today, so a release found
by its source revision alone could meet another branch's equal number and
fill an importer with the wrong version. The record keeps the branch the
reservation came from, and an importer's fill matches both.

Builds: design 47 H2 H-A-558 (2), H-A-551
2026-11-23 12:32:00 +01:00
jschoubben c59b83692d I13c: the state build-edges and the branch-build keys go with outdated
Only outdated read the edges a build of another watched branch kept in the
indexer's state build-edges and the heard keys branch-build.<module>.<branch>:
the state leaves the seat mesh-catalog's definition (its def BuildEdges and
fixture, the generated contracts) and the indexer's manifest, and the
writes, the prune at registration-changed and their test go.

Builds: design 47 H2 H-A-559, H-A-558 (1), H-A-548
2026-11-23 12:31:36 +01:00
jschoubben 1df7a964fc mesh-delivery-pipeline: a mover leaves only for a newer revision's entry (H-A-555, H-A-557)
main.453 ended every build step superseded and moved its movers out for
the newer revision's pipeline, though the superseding entry was of source
140, older than its own: no pipeline delivered them. The runner now reads
its own view of the branch's catalog half when a build ends superseded:
the mover leaves only when that revision is newer than the pipeline's and
names another fingerprint of it. Otherwise the end is passed over, said in
the journal, and the build is asked again at once under a new ask, as a
declined step is; the builder's revision wait holds it.

Builds: design 47 H2 H-A-555, H-A-557
2026-11-23 12:30:19 +01:00
jschoubben c219bfbd0d I13c: outdated goes, with what only it read
The verb outdated leaves the seat mesh-catalog's definition (its def
Outdated, its fixtures, the generated Go and TypeScript, under the form 6
this change raised), the indexer's claim, its tool and its answer, the
answer of other branches' builds with it. The indexer's hearings of
toolchain-agreed and wait-ended, whose state heard keys only outdated read,
go with their consumes in its manifest.

Builds: design 47 H2 H-A-548, H-A-558 (1), H-A-532 (DQ-9), H §747
2026-11-23 12:29:50 +01:00
jschoubben 9c64253b1f mesh-delivery-builder: a build is superseded only by an entry of a newer revision (H-A-557)
The builder's picture lags a step ask whose revision it reads by number:
main.453 asked fp f1b929cd at revision 453 (source 141) while the picture
still held source 140's ee67bdfc as the last entry heard, and supersededBy
judged the newer ask superseded by the older entry. The builder now keeps
the revision beside each entry it heard and supersedes a fingerprint only
by an entry of a newer module graph revision than its own; an older or
equal one is passed over and said once. An older entry heard never
withdraws a newer build either.

Builds: design 47 H2 H-A-557, H-A-555
2026-11-23 12:26:28 +01:00
jschoubben f474987827 I13b: the versions fill, the event versions-filled and the builder's fill wait go
The indexer's first fill of the versions from builder_versions was the only
part that said versions-filled, and the numbering it served is gone. So the
fill, its edges and its call go from the indexer, the event leaves the seat
mesh-catalog's definition, its fixture and the generated contracts (the
seat's form rises to 6), and the builder neither hears it nor waits on it:
it reserves from its own reservations alone.

Builds: design 47 H2 H-A-552, H-A-532 (DQ-9, DMC-5), H §756, G §372
2026-11-23 12:26:20 +01:00
jschoubben d0de4a7497 I14: the release's pins record an npm package's version as they do a Go one's
An npm import of another repository enters an entry's packages as a Go one
does (H-A-546 (3)), but the pins matched only a series' Go module path, so
an npm pin stayed empty and the builder waited out its bound. A series now
pins by its Go module path, or by its package name when it has none.

Builds: design 47 H2 H-A-553 (1), H-A-546 (3)
2026-11-23 12:20:34 +01:00
jschoubben 5b6a6a301b B4: an importer's build takes its package's version from the publisher at the key's origin
A package an import-form entry names with no version (a mover of the same
take-in publishes it) is filled from the reservation of the module that
publishes it at the source revision of the build key's own origin, once its
artifact is published, else from that module's release recorded at that
source revision; never from the newest version a registry seat said
published, so the importer is built against what its own pipeline
publishes. The released record keeps the release's source revision, since
the reservation goes at the release. The registry seat's versions read
before the wait and the newest-heard cache go with that fill.

Builds: design 47 H2 H-A-521, H-A-547 (3), H-A-551, H-A-532 (DMC-1)
2026-11-23 12:19:40 +01:00
mesh-tools 72bb027767 Merge pull request 'A step counts a stopping tool runner as passing (design 47 H2, H-A-542)' (#354) from fix/runner-stopping into main 2026-11-23 11:10:51 +00:00
jschoubben 3df8d9f358 I13a: the indexer's tag floor, its requirements state and indexer_requirements go
The builder's floor, their one caller, went with the numbering from before G
(design 47 H §756; H2 H-A-532 DQ-9): the indexer fills no floor from the seat
git's tags or the package registry seats' versions, keeps no state
requirements from each consumer's go.sum and serves no indexer_requirements.
A floor entry kept before is still read as one at its release (G A-490h).

Builds: design 47 H §756, G §372, H2 H-A-532 (DQ-9), spec 20, 29, 48
2026-11-23 12:09:35 +01:00
jschoubben 8f24d9804b I12: a take-in names no version for a package one of its movers publishes, in an import-form importer's entry
At the take-in the version a mover's pipeline will publish is not released, so
the import-form importer's entry names its package with no version and its
build waits for that pipeline's publish (design 47 H2 H-A-532 DMC-1, H-A-547
Q5); a version-line entry keeps its pins, which its fingerprint takes.

Builds: design 47 H2 H-A-521, H-A-532 (DMC-1), H-A-547 (Q5)
2026-11-23 12:05:53 +01:00
jschoubben fdaeed4d7e I11b: a TypeScript import set takes each imported npm package by its content
The import form of a TypeScript module takes each mesh npm package its reported
set names by the digest the packages state keeps under its npm name (I11a), so
a change of an imported package's files moves it and a change of another
leaves it; the npm import of another repository enters the entry's packages as
a Go one does. fingerprint.Resolve already resolves an import by its exact
name, so the form needs no code of its own: the test holds it.

Builds: design 47 H2 H-A-523, H-A-546 (3)
2026-11-23 12:04:06 +01:00
jschoubben d5af4213c3 I11a: an npm mesh package's digest in the packages state, by its npm name
A TypeScript module's fingerprint takes its imported mesh packages by content
(design 47 H2 H-A-523): a take-in of a repository holding an npm package a held
module imports publishes it in the packages state by its npm name, its
repository and directory those of the module graph entry whose artifact
publishes that name, its digest its files under that path but node_modules and
node --test's test files, its requirements' digest its package.json and lock
file.

Builds: design 47 H2 H-A-523, H-A-532 (DQ-6, DMC-3), H-A-546 (1)(2), H-A-547 (Q4)
2026-11-23 12:02:57 +01:00
jschoubben 23533893bb B2: the builder carries no imports on its done key or its build log
A build module says a module's import set as its build seat's event
imports-reported, which the indexer hears (design 47 H2 H-A-517, DQ-7): the
builder's done key and its build log's end entry no longer carry the imports
a build answered, so nothing reads another part's state for them.

Builds: design 47 H2 H-A-517, H-A-532 (DQ-7)
2026-11-23 11:56:02 +01:00
jschoubben 37e1f3c297 B3: the builder's dead readers of the indexer's packages state go
The builder reads package names from the catalog half's entries alone and never
the indexer's state (design 47 G §348): PackagesState, NamesIn, NamedModule,
Carriers and ModuleOf, which read that state and are wired nowhere, go; the
reservation's name test reads its carriers from the entries.

Builds: design 47 G §348, spec 25
2026-11-23 11:54:00 +01:00
jschoubben 6210384d3a B1b: the builder's numberer and its state versions go; builder_versions answers from the reservations
The numbering from before G goes (design 47 H §756, G §372): the builder keeps
no state versions, marks no numbered entry on a registry seat's word and arms
no numbered version's publish bound; the publishes' findings and the
reservations still hear the same events (DQ-11), and a reserved version's bound
is the reservation's (DQ-10). builder_versions keeps answering, from the
reservations alone (DMC-5): what the seat mesh-builds' reserved answers for a
name and, with a version and a digest, whether that version is reserved or
released with that digest.

Builds: design 47 H §756, G §372, G §381, H2 H-A-532 (DMC-5, DQ-10, DQ-11), spec 29, 41, 48
2026-11-23 11:53:05 +01:00
jschoubben 481d1f255b B1a: the builder's version floor and its wait go
The numbering from before G goes with its floor wait (design 47 H §756): the
builder asks no floor (seat git.tags, the registry seats' versions, the
entries' requirements), keeps no state floor-waits, serves neither
builder_floor_again nor builder_floor_waits, raises no floor-silent finding
and hears no take-in.taken or condition-cleared to wake one. The claim
numbering that asked the floor (Numberer.Number, build.Numbers) goes with it;
the reservation is the one place a version is numbered.

Builds: design 47 H §756, G §372, spec 29, 41, 47, 48
2026-11-23 11:48:06 +01:00
jschoubben 9b8dcc25ce mesh-delivery-sdk: a stopping tool runner's fault is passing, in one place (H-A-542)
A build step's publish met by a tool runner that restarted ended failed (main.440):
PublishFault counted only "no responders" and "bundle exited". sdkstep.IsPassing
now counts a call a stopping tool runner did not take, by its typed fault stopping
(the error's ErrorKind, as mesh-sdk's stdio hands it), so every step's fault reading
and PublishFault's "publish: " why read it the same; a bare "timeout" stays a
failure.

Builds: design 47 H2 H-A-542
2026-11-23 11:47:42 +01:00
jschoubben f8f1c6d378 I10: the indexer's whole test at import grain
The whole test now reports the import sets of two requirers of mesh-sdk: the importer of
buildstep and a requirer importing announce alone. A mesh-sdk commit changing buildstep
moves mesh-sdk, the importer and a module with no report (by its requirement), never the
requirer. The release's re-pin names only the version-line module. The bed's durable hears
the Go build seat's imports-reported, as the manifest's consumes names it.

Builds: design 47 test 80; design 47 G §56; design 47 H2 H-A-520, H-A-521, H-A-528, H-A-530; H-A-532 DMC-7
2026-11-23 11:36:49 +01:00
jschoubben a72428a00f I7: a take-in's movers by import grain
A module of any repository whose import set is reported moves when its fingerprint moved,
and only then: a reported set holding no changed package names no mover. A module with no
reported set keeps the fallback that exists, moving by its requirements.

Builds: design 47 H2 H-A-520, H-A-528, H-A-536, H-A-538; design 47 H §743; ADR 0593 §3
2026-11-23 11:32:18 +01:00
jschoubben 72373ba68d I5: a release re-pins only modules on the version line
repinned names no module whose import form is set: its fingerprint takes no pin, so a
release of a package it imports never moves it; a module on the version line is named as
before.

Builds: design 47 H2 H-A-530, H-A-538
2026-11-23 11:30:51 +01:00
jschoubben 656bc8b5c2 I4: a fingerprint takes of a reported set only what the module graph publishes
At every recompute, and where a report's import form is computed, the import set counts only
the imports a package artifact of the module graph's entries holds (a Go module path or an npm
name, itself or a path under it); any other import is outside the mesh and never sends the
module to the version line. The state imports keeps the reported set whole. A graph state
that cannot be listed keeps no name back, since its nodes name no package.

Builds: design 47 H2 H-A-539, H-A-540
2026-11-23 11:30:00 +01:00
jschoubben 3fffe7e2dd S2: the step runner checks only that an import set is sorted and each once
Nothing in a path or name tells a mesh package apart: mesh Go modules come from the Go
package registry, not the forge. The per-language form check and its settings go
(CheckGoImports, CheckNpmImports, DefaultNpmScope, AskSteps.ImportPrefix and ImportScope);
CheckImports judges every seat's set sorted and each once, and the indexer keeps of it the
packages a module of the module graph publishes.

Builds: design 47 H2 H-A-539 (withdraws H-A-534's form check and H-A-535's settings)
2026-11-23 11:26:47 +01:00
jschoubben 12000b46d1 I9: an entry's import form says its import set is reported
Kind 1 comes from the import set when the entry's import form is set, an absent imports
then the empty set, so a reported empty set gives no kind-1 edge; an entry with no import
form is on the version line and keeps kind 1 from packages.

Builds: design 47 H2 H-A-522, H-A-536, H-A-538
2026-11-23 11:24:46 +01:00
jschoubben 03c3690d54 I4: the import form takes no pin, and a reported set is a key or a held set
The import form's fingerprint takes each imported package by its content and no released
version: a release of the same content leaves it, and a held fingerprint made with a pin
from before stands while its import form is unchanged; only the version line takes the
pins. The import form is chosen when the module's set is reported: a key in the state
imports, an empty set too, or, until its next report, a set its modules value already
holds. An import form with no imports is a valid modules value: it says a reported empty set.

Builds: design 47 H2 H-A-530, H-A-521, H-A-529, H-A-536, H-A-537, H-A-538
2026-11-23 11:23:56 +01:00
mesh-tools 819bc52745 Merge pull request 'Pipelines page: one pipeline by tier and stage; every branch's together, filtered by a module (design 47 H2, H-A-531, H-A-533)' (#353) from fix/view-tiers into main 2026-11-23 10:15:02 +00:00
jschoubben b52a70b1b2 I9: the catalog graph's kind 1 comes from the reported import set
An entry whose fingerprint was computed with an import set gets one kind-1 edge per import,
from the package artifact of the longest name holding it to its artifacts of that ecosystem;
a requirement no import names gives none. An entry with no set keeps kind 1 from packages.

Builds: design 47 H2 H-A-522, H-A-532 DQ-14
2026-11-23 11:14:24 +01:00
jschoubben 2f4fe5fa8b I8: every take-in computes with main's import set, a watched branch's too
The recompute takes each module's set from the state imports (a branch's copy of another
set gives way to it), with main's import form while main's value holds that set, so the form
costs no rebuild; a branch's take-in reads the state through an overlay and drops none of it.

Builds: design 47 H2 H-A-519, H-A-529, H-A-532 DMC-6
2026-11-23 11:13:13 +01:00
jschoubben c0b3e4ad08 S2: the step runner judges an import set by its build seat's language form
A Node build's imports are npm names in the mesh's scope (@novox/mesh-sdk, one package, no
sub-path), a Go build's Go module paths under the forge's prefix; AskSteps.ImportScope and
ImportPrefix carry the build module's settings, trunk.DefaultNpmScope and ForgeModulePrefix
when they name none (trunk.CheckNpmImports, CheckGoImports).

Builds: design 47 H2 H-A-534, H-A-532 DQ-6
2026-11-23 11:10:25 +01:00
jschoubben a770eb5103 Pipelines page: every branch's newest together, filtered only by a module
The operator found a pipelines view filtered by branch name makes no sense:
the page and the terminal view now list the newest pipelines of every branch
together, newest first, the branch a column, and offer one filter, a module
(the pipelines that carry it). A delivery still links to its pipeline from its
branch's list, or from every branch's list by the row's branch.

Builds: design 47 H2 H-A-533 (hq 1b1e1984)
2026-11-23 11:09:42 +01:00
jschoubben 19f06be6c1 Runner's list: each row names its branch, every branch's when none is named
The pipelines page lists every watched branch's pipelines together, the
branch a column of each row, so the short row carries the pipeline's branch;
list already answered every branch when none was named, and its description
now says so. The seat mesh-pipeline-runner's form rises to 11 for the field.

Builds: design 47 H2 H-A-533 (hq 1b1e1984)
2026-11-23 11:09:42 +01:00
jschoubben 9bba3000f3 Pipelines page: a stage's count is of the worst outcome's group
Passed, carried and passed read "passed 2/3", as if one did not pass: the cell
counts the artifacts in the group of its worst outcome (failed, not run,
waiting, running, passed) and shows the count only where fewer than all are in
it, so a cell never reads worse or better than it is.

Builds: design 47 H2 H-A-531 addendum (3), as read in hq d7e7d204
2026-11-23 11:09:42 +01:00
jschoubben f1e4ab1cf6 I3: the indexer reads no imports from the builder's build log
ApplyBuildEnd and its start replay go: a module's import set reaches the indexer only as
imports-reported. The build-log read stays for the module paths and the out-of-step findings.

Builds: design 47 H2 H-A-517, H-A-532 DQ-7
2026-11-23 11:08:54 +01:00
jschoubben b89a65fde6 I2: indexer_imports reads one module's import set
The tool answers the set the state imports keeps for a module, each package with its digest
and the reporting build's fingerprint and commit, or that none is kept, so the module moves
by its go.mod's requirements.

Builds: design 47 H2 H-A-527, H-A-528, H-A-532 DQ-3
2026-11-23 11:08:22 +01:00
jschoubben e2c3cea042 I1: the indexer hears imports-reported and keeps each module's import set
The indexer consumes node-build-go and node-build-node imports-reported; a report of the
fingerprint main's modules state holds for the module keeps the set on the module (Imports,
ImportForm, as the build log path did) and in the new state imports (one key per module,
{module, fingerprint, commit, imports: [{package, digest}]}, the digests the import form is
computed with), deleted with the module's modules key. A report of another fingerprint is
left; one naming no module or fingerprint is said and acknowledged.

Builds: design 47 H2 H-A-517, H-A-518, H-A-519, H-A-527, H-A-529, H-A-532 DQ-3, DQ-4, DQ-13, DMC-2
2026-11-23 11:07:18 +01:00
jschoubben 286f2b668d S1: the step runner says a done build's import set as imports-reported
AskSteps gains SayImports, called once at the end of a build that read its imports
(any branch; the indexer judges the fingerprint), with the module, the fingerprint
asked, the commit and the imports; SayImportsOn publishes it on
mesh.seat.<seat>.event.imports-reported.<node> (buildstep.ImportsReportedSubject),
id per module and fingerprint. A failed say is journalled and leaves the answer
standing; BuildAnswer.Imports stays as the say's input.

Builds: design 47 H2 H-A-517, H-A-518, H-A-532 DQ-2, DQ-7, DMC-2
2026-11-23 11:02:25 +01:00
jschoubben 9b81842090 C1: the build-step part says imports-reported, so a build module can report a module's import set
The build seats gain the event imports-reported.<node> (part build-step, form 4), body
{node, module, fingerprint, commit, imports}, all required, imports possibly empty, kept as
toolchain-reported (90 days, 16 MiB). Fixtures on node-build-go and node-build-node; the
image build module says none.

Builds: design 47 H2 H-A-517, H-A-518, H-A-532 DQ-2, DQ-13
2026-11-23 11:00:22 +01:00
jschoubben 81387d0f3b Pipelines page: one pipeline by tier and stage, and its delivery on each node
The operator read every step of main.417 as passed and took it for delivered
while it had failed on one step and no want was written: the page listed a
pipeline's steps flat, with no tier, no stage and no delivery. One pipeline now
shows a header (outcome, first failure's why, how many movers run their build
on every node they are placed on), then a block per tier with a row per mover,
a cell per stage (the worst outcome over its artifacts, waited, ran and why on
hover) and a cell per node its module is placed on (no want written, wanted,
applying, running the pipeline's build, held with why), in the web page and the
terminal view. The page reloads on the runner's events and on the wants',
haves' and assignments' changes the view already hears.

Builds: design 47 H2 H-A-531, H-A-531 addendum (hq 7dc6592b, f870d24b)
2026-11-23 10:56:14 +01:00
mesh-tools 7a9f3489a5 Merge pull request 'The runner asks no build node for a test step with nothing to run (design 47 H2, H-A-515)' (#352) from fix/nothing-to-run into main 2026-11-23 09:47:11 +00:00
jschoubben cec7d05651 pipeline runner: never ask a test step its build seat's steps says has nothing to run
In main.416 a contracts module's TypeScript package waited about 290 s for a
build node, per step, to answer nothing to run in 1 to 3 s. At placement the
runner now calls each artifact's build seat's verb steps (kept by the
artifact's fingerprint, answered in seconds) with the fetch its steps are
asked with, and ends every lint, unit or integration step of a kind it
answers none for as nothing to run at once: logged, said, asked of no
build node. The other steps are asked as before, beside the build step. A
steps call that fails asks the artifact's steps as before, said in one
journal line. A step placed again after a restart is placed from what its
first placing knew, so a test run keeps its asker.

The build step's record now carries asked-at, as the test steps' do, so
the pipelines page shows how long it waited.

Builds: design 47 H2 H-A-515, H-A-515 addendum, H-A-516
2026-11-23 10:38:30 +01:00
jschoubben 82df41e671 build seats' steps: say lint is answered only where there is something to lint
The verb description said "lint always", while the TypeScript build seat's
lint ends nothing to run for a tree with no TypeScript file; the runner now
reads steps to skip a kind it answers none for, so the description says
what the verb does. The part build-step is shared by the three build seats,
so its one description names Go (always) and TypeScript (only where a
package holds a TypeScript file).

Builds: design 47 H2 H-A-515 second addendum, H-A-515 addendum
2026-11-23 10:38:30 +01:00
mesh-tools 8a21bf5e96 Merge pull request 'Pipelines page: each step's waited and ran, not the asked time as its start (design 47 H2, H-A-516)' (#351) from fix/view-waited-ran into main 2026-11-23 09:26:57 +00:00
jschoubben 09df0bbf36 Pipelines page: each step's waited and ran, not the asked time as its start
The operator read 6 minutes per step where 5 to 6 were waiting for a build
node and 20 s were running: the steps' "started" column showed the time the
step was asked. The web page and the terminal view now show per step the
time it was asked, the time its seat's holder took it and the time it ended,
with how long it waited and how long it ran, from the step record's
asked-at, taken-at and ended.

Builds: design 47 H2 H-A-516
2026-11-23 10:24:46 +01:00
mesh-tools 717a07ddfb Merge pull request 'Forge bridge whole test: read performed once the bridge acknowledged the act (design 47 H2 §807, §812)' (#350) from fix/forge-bridge-owed-once into main 2026-11-23 09:09:54 +00:00
jschoubben 8004bb98f0 Forge bridge whole test: read performed once the bridge acknowledged the act
TestBridgePerformsWhatIsOwedOnce read performed as soon as the first fill
key was purged, while the prune (run inside the write that keeps the act's
outcome) was still purging the others; on a loaded build node the count
landed mid-prune (main.278, 365, 401, 415: "performed holds 37116 bytes of
current values after its prune, want about its target 32768"). Made visible
locally by slowing each purge by 20 ms: the old test fails with the same
words, the new one passes.

The kind is a test acting on the first sign of an act (its owed.ended, one
purge) while the act's work goes on. The test now waits for the bridge's
acknowledgement of the named act on its durable, which comes only after the
outcome is kept and the prune ended: before reading performed after the
prune, and before stopping the bridge after the acts said while the forge
was away (a stop between outcome and keeping hears the act again, writing
performed while the test fills it).

Builds: design 47 H2 §812, §807
2026-11-23 10:02:46 +01:00
mesh-tools d7d22ca67f Merge pull request 'Seat container-image-registry gains name-of: the holder names an upstream copy (design 47 H2, H-A-513)' (#349) from fix/registry-name-of into main 2026-11-23 08:47:45 +00:00
mesh-tools 8bdd78064a Merge pull request 'The builder takes each step ask on a worker of its own and says step-progress (design 47 H2, H-A-514)' (#348) from fix/builder-events-backlog into main 2026-11-23 08:46:19 +00:00
jschoubben bda5a8f6ef Runner: the seat mesh-builds' step-progress arms its ask's bound again
A build step whose build waited for a package ended ask-unanswered after ten
minutes, since only mesh-wants' step-progress armed a bound again. The runner
now consumes and hears the seat mesh-builds' step-progress the same way.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:45:23 +01:00
jschoubben a1a8e7cc34 Builder: hand each event to a worker of the name it carries
The builder handled its events consumer one event at a time, each registry
published and version-released taking seconds, so a pipeline's flood of them
held every later event. Each event now goes to the worker of the name it
carries, one name's events in order and the names side by side; the events
still waiting are said in progress at each end, with no timer.

Builds: design 47 H2 H-A-514 addendum and second addendum
2026-11-23 02:44:21 +01:00
jschoubben b337ee639e Builder: a publish asked again is judged from its record, never a backlog count
The builder held every publish asked again while its events consumer had a
hundred messages unheard; under a pipeline's flood of published events that
held the very publishes the build steps waited on. A duplicate is now judged
from the reservation's recorded publishes and the registries' record alone.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:42:07 +01:00
jschoubben 8abe614271 Builder: a version-released no reservation holds is acknowledged at once
Each version-released listed the module's reservations, one to three seconds
on the serial events consumer, also for a version the builder no longer holds.
Its series' one key now says whether a reservation holds it; one none holds is
acknowledged with nothing listed.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:41:14 +01:00
jschoubben 49bf651e32 Builder: say step-progress every minute while a build step builds or waits
A build step whose build waited for a package said nothing after ask-taken,
so the runner's bound of the ask ended it unanswered. The builder now says the
seat mesh-builds' step-progress of each ask it holds once a minute.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:40:32 +01:00
jschoubben 668ef8d467 Seat mesh-builds: step-progress, said while a build step builds or waits
The runner arms an ask's bound again at each step-progress, which only the
seat mesh-wants said: a build step whose build waits for a package said
nothing for the bound and ended ask-unanswered. The seat mesh-builds gains
step-progress, with the fields of mesh-wants', and its generated contract.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:39:06 +01:00
jschoubben 131dfe71a7 Builder: each step ask is taken and said ask-taken on a worker of its own
The pull of the seat mesh-builds' work queue took each ask in its callback:
the drop read, the take in the state taken and the ask-taken publish of one
ask held every later ask's, so a slow state call delayed ask-taken past the
runner's bound. The pull now only holds the ask and starts its worker.

Builds: design 47 H2 H-A-514
2026-11-23 02:37:38 +01:00
jschoubben 583fdbaf0c container-image-registry gains name-of: the holder names an upstream copy
The node-engine composes an upstream artifact's image from the reference the
registry's holder keeps the copy under; the naming rule is the holder's, so the
engine asks the seat rather than repeat it.

Builds: design 47 H2 H-A-513 second addendum
2026-11-23 01:57:24 +01:00
mesh-tools 5b50f6029e Merge pull request 'The assigner orders a want's writes by the bus revision; run is information (design 47 H2 §813 (1), H-A-504 third addendum)' (#347) from fix/want-order-by-revision into main 2026-11-23 00:51:19 +00:00
jschoubben 440c3c69ae Write a want by compare-and-set on its key's revision; the run is no gate
Wants written before the sequence existed carry a revision number as their run
(322, 323), so the run compare refused every new want of a lower sequence. The
order is now the bus's own: the assigner writes a want with compare-and-set on
the key revision its pass read, a stale pass loses to the newer write and says
so once, and the next pass judges the key again. The run stays in the want as
the pipeline's sequence, information for the why and the tools.

Builds: design 47 H2 §813 (1), H-A-504 third addendum
2026-11-23 01:47:54 +01:00
mesh-tools 41ca769fcb Merge pull request 'A build step whose revision the picture has passed ends superseded too (design 47 H2 H-A-508 second addendum)' (#346) from fix/stale-revision-superseded into main 2026-11-23 00:05:20 +00:00
jschoubben 167eded5f1 A revision read by its number that names a newer fingerprint ends superseded too
The fact is the same whichever check finds it: a kept catalog revision,
read below the picture or by its number, that names a newer fingerprint of
the module ends the step superseded at once, never failed and never sent
into the picture's wait.

Builds: design 47 H2 H-A-508 second addendum
2026-11-23 01:03:27 +01:00
jschoubben e76e49e6a3 A build step whose revision the picture passed ends superseded, not failed
The builder's check of a step's revision against its picture ran before
the judgement of the fingerprint and ended failed when the kept catalog
revision named a newer fingerprint of the module (main.338, 00:57). One
outcome for one fact: such a step ends superseded naming the superseding
fingerprint; failed stays for any other mismatch.

Builds: design 47 H2 H-A-508 second addendum
2026-11-23 01:00:31 +01:00
mesh-tools c0c6228ebb Merge pull request 'The runner's test-runs cap is its bucket's, and the Ager ages ended runs by fill (design 47 H2 H-A-510)' (#345) from fix/test-runs-fill into main 2026-11-22 23:41:37 +00:00
mesh-tools 74bb7b4401 Merge pull request 'The assigner drops a retired module's assignment key: by the tool assigner_assignment_drop and at its pass (design 47 H2 H-A-509)' (#344) from fix/tolerant-state-read into main 2026-11-22 23:41:13 +00:00
jschoubben 93d9d0ea13 Assigner review 1: the drop tool judges every watched branch; the pass row runs the pass
The tool now reads every watched branch's catalog half through the seat
mesh-catalog's verbs registrations and revision, as the pass's world.trunk
holds them; the pass table drives p.wants, so it fails without the clean
state's call; the manifest test names assigner_assignment_drop.

Builds: design 47 H2 H-A-509 (and the lead's answer of review round 1)
2026-11-23 00:36:40 +01:00
jschoubben 3ae5fbdf1a Assigner: drop a retired module's assignment key, by hand and at the pass
A module key of a retired module, written before the value carried a version,
stayed in the assignments state for ever and stopped every reader of the
whole state. The tool assigner_assignment_drop {module, node, why} deletes one
such key, recorded as a hand act first; the pass's clean state drops each
itself, naming it in the journal. Either drops only a key no manifest of the
trunk names whose node key does not name it; nothing goes while the trunk is
empty.

Builds: design 47 H2 H-A-509 (and its second addendum)
2026-11-23 00:36:40 +01:00
jschoubben 2ce0acced1 Runner: test-runs' cap is its bucket's, and the Ager ages by fill
The runner refused every test run once test-runs held 16 MiB, its
setting's default, while its bucket is 64 MiB: seven days of runs never
fit, so every pipeline stopped. The cap is now the bucket's max bytes,
read from the bus (the KV stream's Config.MaxBytes, which runsFill
already read): the bucket is the one truth of the manifest's max-mib,
so the runner keeps no second number and does not read its manifest.

The manifest changes: the setting test-runs-cap-mib, its file resource
test-runs-cap and its environment line go, and test-runs-kept's
default is 48h (code and manifest). At nine tenths of the cap the Ager
deletes the oldest ended runs with their output objects, in the step
log's order from the test runs' retention, until the fill is under
eight tenths, said in one journal line of how many and how old; a run
not ended is never aged by fill.

Builds: design 47 H2 H-A-510, H-A-510 addendum (lead answer)
2026-11-23 00:36:20 +01:00
mesh-tools da20b45a04 Merge pull request 'A build step of a superseded fingerprint ends superseded, an outcome of the seat mesh-builds (design 47 H2 H-A-508)' (#343) from fix/stale-build-step into main 2026-11-22 23:35:51 +00:00
jschoubben a5a7afdfa4 builder: hold the after-the-wait superseded judgement with a withdrawn build
Review round 2: the subtest's build ended done, so the check after the wait
was not held. The build in flight is now withdrawn by the newer entry (the key
ends "withdrawn: … superseded by …", main.327's gate build), and the step
still ends superseded; without the check it ends failed.

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:33:45 +01:00
jschoubben a2b916a896 runner: test the refusal of superseded from another seat and a dependent that stays
Review round 1: a node-build-go end naming superseded is refused as an
outcome the runner does not know, moving nothing; a dependent whose steps
ended not asked on a mover whose build ended superseded is taken out and
placed again.

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:27:52 +01:00
jschoubben 1a19c5c4c1 builder: judge the newest entry first for a build ended now too
Review round 1: a build a newer entry withdrew while it ran still ended the
step failed, and passedWithItsVersion judged supersession only after the
takeover and only when no version was held. Both now judge the branch's
newest entry first and end the step superseded; a release record that
cannot be read answers its error, never "not taken over".

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:27:52 +01:00
jschoubben 367df6cadd runner: a build ended superseded moves its mover out, never a failure
A build step the builder ends superseded is taken as the mover moved to the
newer revision's pipeline, by the path a newer pipeline taking a mover
already has: its other open steps end superseded, the mover is kept in the
pipeline's superseded, and the pipeline is judged by its other movers. Any
other seat's end naming superseded stays refused as an outcome the runner
does not know.

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:27:52 +01:00
jschoubben a1379ef084 builder: a build step of a superseded fingerprint ends superseded, never failed
The builder judged an existing done build only by its reservation, release or
takeover; once the release of the taking-over version deleted the series key,
a stale build of main.327 fell through to "no version is reserved for it".
It now judges the step's fingerprint against the branch's newest entry first,
for a done build as for one not built, and ends the step superseded naming
the superseding fingerprint; those words stay for a current fingerprint, and
the release record keeps the fingerprints it withdrew, so TakenOver answers
after the release.

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:27:52 +01:00
jschoubben b53a3fd575 mesh-builds: a build step ends superseded, never failed, for a superseded fingerprint
The seat mesh-builds' step-ended gains the outcome superseded, its why naming
the superseding fingerprint, so a stale build is not said as a failure of the
change; the seat's form is raised to 2.

Builds: design 47 H2 H-A-508 (and its addendum)
2026-11-23 00:27:52 +01:00
mesh-tools 55ab8a82d0 Merge pull request 'A cancel or an end drops every open ask of the pipeline; one key per ask, read instead of listing the pipelines (design 47 H2 H-A-506)' (#342) from fix/cancel-drops-asks into main 2026-11-22 23:27:29 +00:00
jschoubben bf18ae74cb H-A-506 review 2: only a test run's ask key outlives its pipeline's end
The kept-key rule also kept a mesh-wants composition step's own ask key,
whose shared runs are mesh-wants' and no test run whose end deletes it, so
every ended pipeline left that key for good. A key is kept past the end only
for a test run's ask, the rule DropOpen uses.

Builds: design 47 H2 H-A-506 addendum, H-A-506 corrected
2026-11-23 00:24:47 +01:00
jschoubben ea5abba84d H-A-506 review 1: a shared run's ask key outlives the asking pipeline's end
At a pipeline's end every ask key of its steps went, a shared test run's
among them, while another pipeline still read the run: that reader's
progress found no key and its steps ended could not run. A shared run's key
now goes only with the run's end (EndRun, leaveRun, unmarkAsks), and a late
ask-taken clears a finding only while its pipeline runs (second addendum).
A declined step asked again deletes its earlier ask's key whatever its run.
The last reader's drop of a run's ask is asked beside the leave, its one
journal line saying dropped, or refused or not answered. A re-pin's
holderless end is tested to drop the open asks of the movers it keeps.

Builds: design 47 H2 H-A-500 addendum (1), H-A-506 corrected, H-A-506 addendum, H-A-506 second addendum
2026-11-23 00:18:55 +01:00
jschoubben 8614f0baf7 H-A-506 corrected runner: a shared run's ask is dropped only by its last reader
A cancel or an end leaves each shared test run its steps read, and the run's
ask is dropped only when the leaving pipeline was its last reader, never
while another open pipeline still reads it; its own asks of no shared run
and its mesh-wants asks are dropped at once. A step asked again (a rerun, a
declined step of no test run) deletes its earlier ask's key: one key per
ask, gone once the ask is no longer open.

Builds: design 47 H2 H-A-506 corrected, H-A-506 addendum
2026-11-23 00:00:46 +01:00
jschoubben 9afc8a160d H-A-506 runner: every ask put has an ask key; its events read that key, never the pipelines
An ask-taken or step-progress of an ask with no test-run key listed and read
every pipeline (about 3,850), 1 to 2 s per event on the runner's one consumer.
Now every ask the runner puts gets its ask key at the put, naming its
pipeline, mover, step and run: the test run's ask key of H-A-500 and the key
of every other ask are merged into this one form, `ask.<ask>` in test-runs
(a key written before holds its run alone and still reads). Taken, RunTaken
and RunProgress read that key and the one pipeline it names; an event whose
ask has no key is acknowledged at once, counted in H-A-500's one journal line
per hundred. The key goes with the pipeline's end or its run's end, so a late
ask-taken after the end clears no finding (H-A-506 second addendum).

The drops of an ended pipeline's asks are asked beside the end (the Hearer's
Aside): a seat with no holder answers a kept call only at its bound, which
held the cancel verb's answer past its caller's wait in the queue
integration test.

Builds: design 47 H2 H-A-506, H-A-506 addendum, H-A-506 second addendum
2026-11-22 23:57:08 +01:00
jschoubben 600a4a99a5 H-A-506 runner: a cancel and a placing's end drop every open ask of the pipeline
A cancelled pipeline's asks stayed on the build seats' work queues and the
holders ran them in full: only the last reader's leave of a shared test run
dropped an ask. Now the cancel, and an end at a placing (holderless, a kept
revision gone), drop every ask still open through its seat's drop, a shared
test run's and a mesh-wants step's alike, and leave every test run read; one
journal line per drop or refusal, and a drop not answered fails nothing.

Builds: design 47 H2 H-A-506
2026-11-22 23:47:44 +01:00
mesh-tools 6a550f59f6 Merge pull request 'Every pipeline has a sequence and pipeline-ended carries it; the want's run is that sequence (design 47 H2 §813 (1), H-A-504)' (#341) from fix/want-run-order into main 2026-11-22 22:44:14 +00:00
jschoubben b6702196b8 H-A-504 addendum assigner: a want's run is its pipeline's sequence
runOf took the pipeline key's last segment, an again run's number, so
node-tools 0.1.115 of main.320.again.1 (run "1") was refused on every
node under run "2" of main.265.again.2, an older pipeline. The assigner
now keeps the sequence pipeline-ended says in its end record and the want
rule writes it as the want's run; the compare-and-set and the
node-engine's compare stay as they are. A pipeline-ended without seq is
refused in the journal and keeps nothing; an end kept before this change,
without seq, writes no want and says so once, naming the runner's
end-again of its pipeline as the recovery.

Builds: design 47 H2 §813 (1), H-A-504 corrected, H-A-504 addendum, H-A-504 second addendum
2026-11-22 23:35:51 +01:00
jschoubben f6aff0182c H-A-504 addendum runner: every pipeline has a sequence, and its end says it
The runner took queue.next only for a pipeline that waited, so most
pipelines kept seq 0 and the assigner had no order across pipelines for a
want's run. queueStart now takes the next sequence for every pipeline it
writes, queued or placed at once, and pipeline-ended carries the record's
seq.

Builds: design 47 H2 §813 (1), H-A-504 corrected, H-A-504 addendum
2026-11-22 23:35:43 +01:00
jschoubben ed0b905767 H-A-504 addendum contracts: pipeline-ended carries the pipeline's sequence
The assigner had no sequence to write as a want's run: pipeline-ended said
no seq, so it took the key's last segment, an again run's number, and
refused node-tools 0.1.115 of main.320.again.1 under run "2" of an older
pipeline. pipeline-ended gains seq, the record's; the record's seq is now
said to be taken for every pipeline. The runner seat's form is 10; the
contract is regenerated, with a fixture of an again pipeline's end.

Builds: design 47 H2 §813 (1), H-A-504 corrected, H-A-504 addendum
2026-11-22 23:27:19 +01:00
mesh-tools 28726acaaf Merge pull request 'The indexer's packages integration test follows H-A-495: a pin moves on a release, never on a reservation (design 47 H2 H-A-495, §805)' (#340) from fix/stale-integration-tests into main 2026-11-22 22:24:16 +00:00
jschoubben 7bacccf562 H-A-495 indexer test: the release re-pins the importer, a reservation moves no pin
TestASourceRevisionMovingMeshSDKNamesItAndItsImporters still expected the
twenty reservations' pipeline-started to keep a re-pin revision pinning
importer to the reserved version, which H-A-495 ended (repin_test.go was
brought in line, this bed was not), so it failed on every pipeline with
"main.5 is not kept after 20s". The bed now waits for the indexer's
acknowledgement of each pipeline-started (its settle moves nothing), then
releases the version: the Go package registry seat's published and every
artifact's package-published. The next revision must be the release's
re-pin, importer its mover at that version. The harness's events durable
now also hears the registry's published, as the manifest's consumes names it,
and this bed keeps package-published on its stream and the state versions.
Fails with the pre-H-A-495 pin rule (main.5 is the reservations' re-pin).

Builds: design 47 H2 H-A-495 and its addendum, §805
2026-11-22 23:18:17 +01:00
mesh-tools 29c4673ad1 Merge pull request 'The runner hears a take-in on its own durable and acknowledges a late event of an ended ask at once; a held key-ttl state gets per-message TTL (design 47 H2 H-A-500, H-A-501)' (#339) from fix/runner-consumer-ttl into main 2026-11-22 22:07:31 +00:00
jschoubben a8240f5549 Runner: a takeins bind that failed is bound again on registration-changed, not on a timer
A takeins bind that failed was tried again every five seconds. Nothing in the
mesh waits on a timer for another part: the runner binds its takeins durable
at its start and again on each registration-changed, as the indexer binds a
branch's consumer, and says each failed bind; until bound, the main durable
works each take-in.

Builds: design 47 H2 H-A-500 fifth addendum
2026-11-22 23:03:41 +01:00
jschoubben 5792e83bc6 Runner: the Ager deletes an aged test run's ask keys with the run
The ask key ask.<ask> is created with the run and deleted with it, but the
Ager deleted an aged run and left its ask keys in test-runs for good; only a
run whose last reader left lost them. The Ager now holds the run clock and
unmarks the aged run's ask keys as the Hearer does.

Builds: design 47 H2 H-A-500 addenda (1)
2026-11-22 23:02:05 +01:00
jschoubben 678d8fa5b3 Runner: a take-in said before the takeins durable is bound is still worked
The takeins durable delivers from the moment it is made, so a take-in said
while the runner was down reached only the main durable, which acknowledged
it with no work: that take-in started no pipeline. Until the takeins durable
is bound, the main durable now works each take-in.taken; from the bind, it
acknowledges with no work those the takeins durable delivers, told apart by
the stream sequence the durable delivers after, so a take-in still waiting on
the main durable is worked whatever the moment it is heard.

Builds: design 47 H2 H-A-500 fourth addendum
2026-11-22 22:59:21 +01:00
jschoubben b2d9d1ac90 Runner: take-in.taken is heard on a durable of its own
The runner heard every event on one serial durable, so a take-in waited behind
hundreds of late step events and its pipeline started ten minutes late. The
runner now makes its own durable <node>_<module>_takeins on EVENTS, filtered
to take-in.taken, and acts on a take-in there alone; the main durable
acknowledges a take-in at once with no work. The test-runs integration test
keeps the runner's findings on their own stream, as the manifest declares:
on EVENTS each reached the main durable unhandled and wrote event-unhandled
again, a flood the take-in now overtakes.

Builds: design 47 H2 H-A-500 (b) and its addenda (2), third addendum (Q2)
2026-11-22 22:53:04 +01:00
jschoubben 6ffddedfbf Grants: every module is granted its own takeins durable on the events stream
A module that hears take-in.taken behind a long run of other events hears it
late; it now hears it on a durable of its own, <node>_<module>_takeins, which
it makes itself. Every module principal, on its own account or carried by a
tool runner, is granted the create, information, pull and acknowledgement of
that one name on EVENTS, none special-cased.

Builds: design 47 H2 H-A-500 (b) and its addenda (2), third addendum (Q1)
2026-11-22 22:27:39 +01:00
jschoubben 146b9b4ff8 Grants: a held bucket of a key-ttl state gets per-message TTL
The indexer's state heard is declared key-ttl, but its bucket was made before
that declaration, and grants' handling of a held stream only added subjects,
raised caps and moved a source filter: every version-reserved the indexer
kept with a time to live was refused (per-message TTL is disabled, 10166) and
given up after five tries. A held bucket whose state is declared key-ttl now
has per-message time to live turned on, add-only like the cap raise, once per
manifest, and said as asserted; the indexer's TTL stays.

Builds: design 47 H2 H-A-501 (corrected)
2026-11-22 22:22:31 +01:00
jschoubben 1d0a40592b Runner: a late event of an ended test run's ask is acknowledged at once from its ask key
Every ask-taken and step-progress listed and read every pipeline to find its
test run, so after a cancel hundreds of late events of ended runs cost one to
two seconds each and held the runner's one event consumer for minutes. The
state test-runs now keeps an ask key ask.<ask> holding the run's key, written
with each ask a run is given and deleted with the run; an event of an ended
run's ask is judged from that key and the run alone and acknowledged at once,
one journal line per hundred.

Builds: design 47 H2 H-A-500 (a) and its addenda (1)
2026-11-22 22:19:34 +01:00
mesh-tools 7be95905f2 Merge pull request 'A pipeline's kept revisions are pinned; a lost one ends the pipeline loudly; the held take-in chain is visible (design 47 H2 H-A-496, H-A-497)' (#338) from fix/kept-revision-pins into main 2026-11-22 20:59:29 +00:00
jschoubben 04fe2e30fe H-A-497 indexer: a hand ask of a held branch answers at once
indexer_take_in_pending ran the whole chain of held take-ins inside the one
loop that acts on the takeins asks, minutes long, so its answer was cut and a
second ask waited behind it and answered "holds no source-moved". The ask
now starts the chain beside the loop and answers at once, "chain started at
source <n>, <m> wait"; an ask that meets a running chain answers its state.
The chain's state (branch, source being taken in, since, how many wait) is
the key chain.<branch> of the takeins state, written at each step and
deleted at the chain's end, skipped by the asks' loop and shown by
indexer_pending. A key a stop left is deleted at the indexer's start.

Builds: design 47 H2 H-A-497 (corrected), its addendum and its second addendum
2026-11-22 21:58:07 +01:00
jschoubben 52ad5af1e9 H-A-497 indexer: say each held source the chain takes in next
The indexer already takes a branch's held sources in order in one pass, but
nothing said so: on 22 Nov one hand ask took 114, 115 and 116 in turn, about
four minutes each, and it looked as if each needed its own hand call. Each
take-in the chain starts after one landed is now a journal line, "held
source <n> of <branch> taken in next, after <n-1>".

Builds: design 47 H2 H-A-497 (corrected)
2026-11-22 21:28:45 +01:00
jschoubben cd16358b21 H-A-496 indexer: pin the revisions a pipeline's movers are kept at
The indexer pinned only a pipeline's own revision, so JudgePins removed
revision 292 while main.291's kept mover still had to read it. HeardPins now
pins every revision pipeline-started names in kept under the pipeline's
record, takes the latest started (said again at a re-pin) as the kept set,
freeing a kept revision it no longer names but never the pipeline's own or
its validate base, and pipeline-ended frees them all. JudgePins is
unchanged.

Builds: design 47 H2 H-A-496, H-A-496 addendum
2026-11-22 21:25:33 +01:00
jschoubben 0c2ead025d H-A-496 runner: say kept revisions; a gone kept revision ends the pipeline
main.291 held the one pipelines-at-once turn 50 minutes waiting for kept
revision 292, which the catalog had removed: nothing pinned it and the wait
had no end. pipeline-started now carries every revision the pipeline's movers
are kept at, and a re-pin says it again with the full list, so the indexer
pins them. A catalog read answered "no such object" is the revision gone;
the placing then ends the pipeline failed "kept revision <r> gone", its
movers are left unfinished and rejoin the next pipeline, and its turn is
freed.

Builds: design 47 H2 H-A-496, H-A-496 addendum
2026-11-22 21:23:48 +01:00
jschoubben 5ab9bd9acc H-A-496 contracts: pipeline-started carries the movers' kept revisions
The indexer pinned only a pipeline's own catalog revision, so a revision a
re-pin kept a mover at could be removed while the pipeline still read it
(main.291 waited 50 minutes on removed revision 292). pipeline-started now
carries kept, every revision the pipeline's movers are kept at, said again in
full at each re-pin, so the indexer can pin them. The runner seat's form is
9; the contract is regenerated.

Builds: design 47 H2 H-A-496, H-A-496 addendum
2026-11-22 21:17:08 +01:00
mesh-tools dc33ae26bb Merge pull request 'mesh-delivery-sdk: registry transfers finished or taken over; missing output said (design 47 H2 H-A-481, H-A-482)' (#337) from fix/transfers-and-output into main 2026-11-22 20:05:01 +00:00
mesh-tools a096397928 Merge pull request 'mesh-delivery-builder, mesh-delivery-indexer: upstream artifacts by pinned digest; newest entry only; no git tag (design 47 H2 H-A-486, H-A-487, H-A-489, H-A-492, H-A-494)' (#336) from fix/upstream-release into main 2026-11-22 20:04:59 +00:00
mesh-tools 5548fff81f Merge pull request 'mesh-grants, mesh-delivery-assigner, mesh-delivery-indexer: the tool runner's twin from the membership; a pin names a released version (design 47 H2 H-A-472, H-A-490, H-A-495)' (#335) from fix/tools-twin-membership into main 2026-11-22 20:04:57 +00:00
jschoubben 52fa062e92 H-A-494: the builder writes no git tag at a release and numbers from no tag
A Go package comes from the Go package registry alone, so a released version
is no longer written as a git tag: the release path and the start's take-in
of a released version call no seat git, and a reserve numbers a series from
the catalog's versions and the registries' only, never reading tags. A
reservation's kept tag field stays for records written before.

Builds: design 47 H2 H-A-494 (withdraws H-A-484's tag steps and H-A-493; design 51's fallback tag retired)
2026-11-22 20:56:51 +01:00
jschoubben ef32d60a5e Indexer: a pin names a released version only, never a reservation (H-A-495)
Importers were pinned to mesh-delivery-contracts 0.1.82 to 0.1.84, reserved by
builds a competing build withdrew before release and never published, so their
builds failed "unknown revision". The series' numbered version a reservation
writes no longer pins: a pin is the series' newest released version, so a
version-reserved moves no pin and the release's re-pin moves the importers. A
pin held on a version never released is moved at the next take-in or re-pin and
said per module ("<module>: pinned to <pkg> <v>, never released; moved to <v2>").

Builds: design 47 H2 H-A-495 and its addendum (hq 9e0923ce)
2026-11-22 20:48:32 +01:00
jschoubben cfd2afe39c H-A-492: the record's bound is a setting; a build key read error is said
Review round 1 (principle 11, configurable, never hard-coded): the bound of
the record of a version's digests is the builder's setting
record-bound-seconds (default 60), read from its file as revision-wait and
package-wait are, set on the Builder and used for the record. A build key
the builder cannot read, or that holds no build, is said in its journal
instead of being taken silently as not done (principle 3, failure is loud).

Builds: design 47 H2 H-A-492
2026-11-22 20:25:03 +01:00
jschoubben 21daeb8893 H-A-492: record a version's digests under the builder's own bound
A takeover or an end cancelling a build's context cancelled the record of its
reservation's digests eight times in a day, each leaving a passed build
unreleased. The record now runs under the builder's own bound (one minute,
not cancelled with the build), and a done build whose digests are not
recorded is recorded from its done key at the builder's next look and at its
start (before H-A-484's start check holds it against the released versions),
said each time.

Builds: design 47 H2 H-A-492
2026-11-22 20:17:14 +01:00
jschoubben ae1bf2098d Assigner: a put's want names the version released at its build (H-A-490 addendum)
A put wrote its want by fingerprint alone, which the node-engine cannot
compose. The put now finds the version released at its build's parts, as the
pass does, names it in the want, and is refused when none is released.

Builds: design 47 H2 H-A-490 (addendum)
2026-11-22 20:04:34 +01:00
jschoubben f09bd2668a Assigner: a passed pipeline takes a mover's version released before the pass (H-A-490)
An again pipeline on a built, published key ends naming no version, and the
runner never says its end again, so its movers kept the old want. At the pass,
a mover with no version is matched to the release of its build's parts.

Builds: design 47 H2 H-A-490
2026-11-22 19:57:15 +01:00
jschoubben 82156f8128 mesh-grants: a never-read durable is an orphan; both twins judged where uncomposed
Review round 2: a durable nobody ever read (no pull waiting, no delivery ever) was
named behind when its twin was not current, and the plain durable of a module whose
program left was never judged (live: claude-code's plain durables 1,000 to 3,000
behind beside a current `_tools` twin). A never-read durable is now an orphan
whatever its twin; one read once and lagging stays behind. The pass judges both
twins of every heard entry wherever no pass composes them, also on a stream where
only such durables are held.

Builds: design 47 H2 H-A-472 (eleventh addendum)
2026-11-22 19:54:25 +01:00
jschoubben ffa58e51c4 H-A-489: test the withdrawn step answer and the look before reserving
Review round 1 found two paths untested: a step ask of a withdrawn key
still newest answers failed at once, and a newer entry heard between the
older build's claim and its reservation is not taken over. Each row
fails without its line. The comments of H-A-205 say that H-A-489
overrides it once the newer entry is heard.

Builds: design 47 H2 H-A-489 (review round 1)
2026-11-22 19:51:59 +01:00
jschoubben cc1034630f mesh-grants: the consumers pass judges the tool runner's held twins too
Review round 1 found that with no `_tools` twin composed, the behind and orphan
checks never looked at one: live, five twins on EVENTS held 1,000 to 58,000
messages and none was named. The pass now reads, on the streams each consuming
module's heard entries name, every held `<consumer>_tools` and judges it as any
consumer: behind by the bound, or an orphan when no pull waits and its twin is
current. The stale comments on HasProgram and the orphan finding's text follow.

Builds: design 47 H2 H-A-472 (tenth addendum)
2026-11-22 19:47:49 +01:00
jschoubben 73cb9ba690 H-A-489: build only a branch's newest entry; withdrawn is final
Two fingerprints of one module took the series from each other (nats
flipped between 0.1.140 and 0.1.152): a later look built an older
fingerprint again, and its reservation took the newer one's over.

The builder now refuses, before it reserves or builds, a fingerprint of
the first watched branch that is no longer the newest entry heard there,
saying once per key that it is superseded; a step ask of it fails so,
never waits. It looks again just before it reserves. A key withdrawn is
taken again by no look, only by a person's build again.

Builds: design 47 H2 H-A-489
2026-11-22 19:45:03 +01:00
jschoubben fcac1fc5d0 H-A-487: prove a listing reads no history when its entries carry no time
Review round 1 found the fingerprint guard of the build read unproven: every
entry of the 100-key listing carried a time. The listing is now also read with
entries that say none, and no history may be read.

Builds: design 47 H2 H-A-487 (review round 1 finding)
2026-11-22 19:37:22 +01:00
jschoubben db899d8ad4 H-A-487: a module's builds are read without every key's history
builder_build read every key's whole history to learn when its entry was
written, one more round trip per key of the module; on nats's hundreds of keys
the read crawled. Each entry's own write time now comes with the key's read,
the history is read only for the one key a fingerprint names when its entry
says no time, and a listing cut at the 20 newest says so in its note.

Builds: design 47 H2 H-A-487
2026-11-22 19:30:59 +01:00
jschoubben 4ca6e478a6 mesh-grants: the membership carries the tool runner's twin spec; no twin composed
The grants part stays the one composer of filters while the tool runner makes its
own `_tools` twin: each heard entry, EVENTS included, carries the twin's filters
(the again filter named for it), ack wait, max deliver, max ack pending and
deliver policy. The pass composes no `_tools` consumer any longer, so it makes no
twin nothing reads; the reader grants add the create and delete of the module's
own twin by name. A membership of a module no longer assigned on its node is
withdrawn by a whole pass, so the runner there removes that module's twins. The
part's own hearing loop leaves EVENTS to the hub, now that the membership names it.

Builds: design 47 H2 H-A-472 (fifth, sixth, seventh, eighth and ninth addenda)
2026-11-22 19:30:19 +01:00
jschoubben 564fd5e0bb H-A-486: an upstream artifact needs no publish to release
Design 51 copies an upstream image by its pinned digest, and distribution's
mirror says published with no version, so nats, hello-web, mailu and showcase
could never be released. The reservation keeps its upstream refs (Upstream,
filled at the reserve from the plan's upstream tasks) and Missing never awaits
them; the indexer releases a version once every other artifact is published,
naming each upstream artifact with the pin its manifest gives, and refuses the
release loudly when an upstream artifact names no pin.

Builds: design 47 H2 H-A-486, H-A-486 (addendum)
2026-11-22 19:26:22 +01:00
jschoubben dc6dfef6f0 A reopen drops without a store only when the holder holds the file (H-A-481 second addendum)
The drop without a second store judged from the parts the holder holds,
and distribution's Holds answers per layer: a publish cut before its
store, whose layers were held, was dropped and never said as published.
The drop now asks the holder's own HoldsWhole (the file at its name and
version); nil never drops, and the reopen finishes as usual.

Builds: design 47 H2 H-A-481 second addendum
2026-11-22 19:25:40 +01:00
jschoubben 8eee17a368 A reopen verifies its parts; the takeover bound is a field (H-A-481 addendum)
A reopen that lacked nothing finished from the held set without reading
the chunks back, so a finish cut after its chunks were dropped, or after
its store, stored wrong bytes or stored twice. Now each part taken is
read back and hashed against its digest as a take does, a failing part is
lacked again, and a transfer whose every part the holder already holds is
dropped without a second store. The takeover bound is the receiver's
field TakeOver, two minutes by default, as its sibling bounds.

Builds: design 47 H2 H-A-481 addendum; review round 1 findings (1), (2)
2026-11-22 19:21:47 +01:00
jschoubben 2b79ee1593 A missing output is said as missing; a failed build keeps its error (H-A-482)
The verb output failed "holds no header" on an empty object, since the
runtime's object read answers an absent object as empty data without an
error: an empty object is now no object, said "the ask kept no output".
A failed build kept nothing for the verb output to answer: it now keeps
its error text, as the build module bounded it, as the ask's output
object with the header a test step's carries.

Builds: design 47 H2 H-A-482, H-A-482 addendum (a)
2026-11-22 19:14:02 +01:00
jschoubben 9931d4f900 A transfer is finished or taken over, never left open (H-A-481)
An opener that opened a transfer again with nothing lacked was answered
"nothing lacked" and the transfer never finished; another caller with the
same digest was refused; and a transfer lacking nothing at its open was
finished without its idle bound, so a restart during the finish left it
open. Now a reopen with nothing lacked finishes it, by its opener or by
another caller; a transfer that lacks a part is taken over by another
caller once its last part is older than two minutes; and the idle bound
is armed before every finish at an open.

Builds: design 47 H2 H-A-481
2026-11-22 19:12:33 +01:00
mesh-tools 18136ce063 Merge pull request 'The builder re-reads released versions at start and waits the pause on a refused tag; one parse of every pipeline key form (H-A-484, H-A-485)' (#334) from fix/tags-and-again-tiers into main 2026-11-22 18:06:50 +00:00
jschoubben a5495bb15e Read every pipeline key form by one parse; the assigner moves an again pipeline's tiers (H-A-485)
The assigner took a tier progress for `pipeline.<branch>.<revision>` only (two dots), so
the progress of a pipeline started again at the head, `<branch>.<revision>.again.<n>`,
was never moved and read as an empty end: its later tiers were never wanted. One parse
of the runner's seat's key forms (mesh-delivery-sdk pipelinekey, over the contract's key
parsers) now reads a pipeline's key for the assigner's tier progress and the runner's
mover keys; a pipeline-ended whose key is of no form is refused loudly and nothing of
it is kept.

Builds: design 47 H2 H-A-485
2026-11-22 18:54:40 +01:00
jschoubben 5d3164b5b7 Builder: take a released version the catalog holds at the start; a refused tag waits the pause (H-A-484)
A version-released whose tag the seat git's holder refused was handed back at once,
spent its five deliveries in seconds and was dropped by the bus: its reservation stood
and its publish item asked again every 30 s for ever. At the start the builder now holds
every built, unreleased reservation against the catalog's verb versions and takes a
released one in as its version-released would (tag, release, bound and item ended,
findings cleared); a refused tag is handed back with the publish pause. The tag check
itself is the forge module's, already accepting a nested package path on the catalog's
trunk.

Builds: design 47 H2 H-A-484, H-A-484 addendum
2026-11-22 18:49:52 +01:00
mesh-tools 96d8136e2b Merge pull request 'The builder's publishes have one consumer per holder; publish_first retired (H-A-483)' (#333) from fix/publishes-one-consumer into main 2026-11-22 17:39:50 +00:00
jschoubben c45f1621fb Seat mesh-builds: publish-queue lists in stream order (H-A-483)
The verb's description and its answer's class and list say what the
builder now does: one consumer per holder, items listed in stream order,
no class pulled first. Description only, regenerated with seatgen; the
seat's format stays, as at B4's description changes of this seat.

Builds: design 47 H2 H-A-483 third addendum, §793
2026-11-22 18:30:30 +01:00
jschoubben fd2cb13961 Publish queue: retire builder_publish_first, list in stream order (H-A-483)
With one consumer per holder an item has no class to move ahead of, so
builder_publish_first, its mode and its act go. The verb publish-queue
lists the items in stream order, the order the one consumer gives them,
and its description says so. A holder is a module name, so one ending in
-live or -again (an earlier release's class durable) is refused at the
learn, said, instead of having another holder's durable deleted.

Builds: design 47 H2 H-A-483 third addendum, §793
2026-11-22 18:28:55 +01:00
jschoubben 915a54f136 Publish queue: one pull consumer per holder (H-A-483)
The two class consumers (live, again) could not order live before again
under every scheduling: the idle-dispatch row failed on the build node
after four review rounds. One consumer per learnt holder (publishes-<holder>)
gives items in order; a failed send is handed back with its pause, so an
item put meanwhile goes first by construction. The builder retires the
holder's class durables of the earlier release before making the one,
since a work queue refuses overlapping filters; their unacknowledged items
reach the one consumer. The gap read, the held again items and the live
in-flight check go.

Builds: design 47 H2 H-A-483, its addendum and second addendum, §793
2026-11-22 18:20:06 +01:00
mesh-tools 1c0309df23 Merge pull request 'The assigner's blocked-keeping test waits for the keeping (H-A-476)' (#332) from fix/assigner-test-race into main 2026-11-22 15:34:10 +00:00
mesh-tools 7dd2891f32 Merge pull request 'A failed mover is started again at the head; a reopening pins its revision again (H-A-479)' (#331) from fix/runner-start-modules into main 2026-11-22 15:34:08 +00:00
mesh-tools b7e364e47b Merge pull request 'grants-for answers from what it kept; the runner's widens bound 30 s (H-A-478)' (#330) from fix/grants-for-kept into main 2026-11-22 15:34:04 +00:00
jschoubben dca2545eb7 H-A-479 third addendum: a reopening never builds beside an open pipeline
A rerun that would reopen an ended pipeline while another open delivering
pipeline carries one of its movers at the same revision is refused with
"its pipeline <key> is running", nothing asked, so one entry is never built
side by side. Tests now cover the two paths review round 2 found untested:
the indexer keeps a revision's gathering while another pipeline's
reservation is left and removes it with the last, and a test step's rerun
reopening an ended pipeline says pipeline-started before its run is started
again.

Builds: design 47 H2 H-A-479 third addendum, H-A-479 second addendum, H-A-479 addendum (2); review round 2
2026-11-22 16:29:24 +01:00
jschoubben bd5852b817 H-A-479 second addendum: own movers withdrawn, no side-by-side start, unbounded n
A pipeline ending not passed withdrew every reservation of its revision, so
an again pipeline's failure could withdraw the head's take-in pipeline's
reservations and the other way round. The indexer now withdraws only the
reservations of the ended pipeline's own movers, read from the movers its
pipeline-ended carries, and withdraws the revision's gathering only when
none is left. A start with modules is refused for a module whose head entry
a pipeline still runs ("its pipeline <key> is running"), and takes the next
n without a bound. A rerun reopening an ended pipeline says its
pipeline-started before the step is asked again, so the revision is pinned
before anything reads it. Tests now cover the again form through the
branch's key forms and a release written into a passed again pipeline.

Builds: design 47 H2 H-A-479 second addendum, H-A-479 addendum (2); review round 1
2026-11-22 16:21:31 +01:00
jschoubben 1bfd54425b mesh-grants: kept grants are keyed by revision and inputs, bound tested
A revision's kept grants carry the digest of the inputs they were
composed with; an ask whose inputs differ composes again, so grants-for
never lists a change the candidate did not cause. TestGrantsForKeepsWhatItMay
now proves that a revision dropped beyond the bound has no grants kept
either (review round 1); the Logf comment says the tools program's
journal too.

Builds: design 47 H2 H-A-478 second addendum
2026-11-22 16:13:08 +01:00
jschoubben c6c86801ca H-A-479 (2) runner: a rerun reopening an ended pipeline pins its revision again
The indexer pins a pipeline's revision from pipeline-started to
pipeline-ended, so a rerun of a step in an ended pipeline (main.258's
composition at 14:41, after its end at 14:15) asked a step against a
revision the catalog had already removed. A rerun of an ended delivering
pipeline now reads its revision fresh through the catalog seat's verb
revision first and is refused by name, nothing asked, when it is gone
("its revision <r> is gone; start the mover again at the head"); once
reopened it says its pipeline-started again, so the indexer pins the
revision until its next end.

Builds: design 47 H2 H-A-479, H-A-479 addendum (2)
2026-11-22 16:08:57 +01:00
jschoubben 33feb148ce H-A-479 (1) runner: start with modules starts a failed mover again at the head
A module whose pipeline failed at an unchanged entry was never carried again
until its fingerprint moved, since start refused the head whose pipeline
existed. The start verb now takes modules: the named modules whose newest
entry has no passed pipeline are started at the head's revision, at the
take-in's tiers, keyed <branch>.<revision>.again.<n> (n from 1, written on
absence); a module whose newest entry passed, or that the head holds no
entry of, is refused by name, nothing started. Exactly one of module or
modules is given. The new key form is read by every key-form list (the
sweep's, a release's, the mover keys'). The runner seat's form is 8; the
contract is regenerated.

Builds: design 47 H2 H-A-479, H-A-479 addendum (1)
2026-11-22 16:05:27 +01:00
jschoubben f44442097c mesh-delivery-pipeline: widens-read-bound defaults to 30 s
A cold grants-for (one composing a revision's grants the grants part did
not keep yet) took 3 to 4 s against the 5 s bound and was cut three times
on 2026-11-22; the bound becomes 30 s in the manifest and the code.

Builds: design 47 H2 H-A-478
2026-11-22 16:01:46 +01:00
jschoubben 1f765ef17b mesh-grants: grants-for composes each revision's grants once
grants-for composed every module twice per ask (3 to 4 s against the
runner's 5 s bound, cut three times on 2026-11-22). The tools program
that serves it now keeps each kept revision's composed grants beside the
revision (the newest's and the candidate's), bounded by
grants-for-revisions-per-branch, so a second ask for a kept revision
composes nothing; it reads its inputs at each ask and journals each
stage's time on its standard error.

Builds: design 47 H2 H-A-478, H-A-478 addendum
2026-11-22 16:01:39 +01:00
jschoubben 203454b1a9 Assigner test: read the keeping's need only once the keeping took it
TestAPassWritesWantsWhileAKeepingIsBlocked read the graph's need right after
two passes, while the keeping takes it on its own goroutine; on a loaded build
node it read too early (pipeline main.251). The blocked object bucket now says
when a keeping meets its gate, and the test waits on that, bounded by the
level bound, as it does on the pass and the wake.

Builds: design 47 H2 H-A-476
2026-11-22 14:59:47 +01:00
mesh-tools b691428ffc Merge pull request 'Builder: the publish dispatch sends live first at one processor; judge test row; done-key test bound (H-A-465, H-A-469, H-A-473)' (#329) from fix/main-tests into main 2026-11-22 13:44:24 +00:00
mesh-tools a41a7c2862 Merge pull request 'Orphaned durables: removable by the bus module, left out of the behind check, not composed again (H-A-472)' (#328) from fix/orphan-durables into main 2026-11-22 13:42:31 +00:00
jschoubben 7e103f3221 Builder: with again items held, fetch live once more before the gap read
A live item put after the turn's live fetch and before the again items were held
was not yet delivered at the gap read, so no gap showed and the later again item
went first (review round 3 on c37a7317, publishitem.go:792-809). With again items
held the dispatch now fetches live without waiting once more: what it returns runs
and the again items stay held; only an empty fetch leads to the gap read. The test's
idle-dispatch case is a subtest of its own, so it runs alone.

Builds: design 47 H2 §793, H-A-473 (third addendum)
2026-11-22 14:40:17 +01:00
jschoubben c37a7317b7 Builder: every again fetch and gap read follows a live fetch
On the turn after an again item ran, the dispatch fetched again and read the live gap
without fetching live first, so a live item the stream held but had not yet given to
the waiting live pull showed no gap and a later again item went first (review round 2
on b77b70a6, publishitem.go:791). The live consumer is now fetched without waiting on
every turn no live item is held. The test row adds that case and bounds its rounds by
the level's set-up share.

Builds: design 47 H2 §793, H-A-473 (third addendum)
2026-11-22 14:35:41 +01:00
jschoubben b2c9e60ac3 Grants: the bound of a current twin is the setting twin-current-hours
Review round 1: the day after which a twin is no longer current was a
constant here and again in the bus module. It is now the setting
twin-current-hours of the manifest (24 by default), written into a file
the part reads at its start, the field name the bus module's manifest
names too, so the operator sets it once per module alike; the
durable-orphaned condition names the bound. hasOwnProcess no longer sits
under ownServesOf's doc comment.

Builds: design 47 H2 H-A-472 (2) and its third addendum (2); review round 1 findings (2), (3)
2026-11-22 14:34:06 +01:00
jschoubben b77b70a66c Builder: an again item waits for a live one in flight to the idle dispatch's waiting pull
The idle dispatch keeps a waiting pull on each consumer, the bus's only wake for an
item put or delivered again. A live item the waiting pull was given but the dispatch
had not yet received let an again item go first (review finding on 1f33a4c0,
publishitem.go:700, 761, 797). An again item taken while the live pull waits now runs
only once the live consumer's delivered sequence is no further than the live items
received; a gap holds it until the live item arrives and runs.

Builds: design 47 H2 §793, H-A-473 (third addendum)
2026-11-22 14:30:22 +01:00
jschoubben 7f5f175b05 Builder whole test: done builds under the level's set-up bound; the hang at its own
The test ran the builder at a 1 s step bound throughout, so a loaded build
node could fail a build that must end done. Those builds now run under
testbus.SetupBound; the hung step's part starts the builder again at 1 s,
and the build again after it under the set-up bound.

Builds: design 47 H2 §793; H-A-473 (addendum)
2026-11-22 14:16:37 +01:00
jschoubben 1f33a4c04f Builder: the publish dispatch pulls the live consumer itself, then the again
The dispatch read the live consumer's pending count against items the
pull's callback had not yet handed it, so at one processor an again item
was sent before a live one already delivered. It now fetches the live
consumer without waiting and pulls the again consumer only when that
returns nothing; an item is received when its fetch returns it.

Builds: design 47 H2 §793; H-A-473
2026-11-22 14:14:15 +01:00
jschoubben 49c656a4ce Grants: compose a module's program consumer only where it names a program
The pass made <node>_<module> beside <node>_<module>_tools for every
consuming module, so a module whose events only the tool runner reads
got a durable nobody pulls, which piled up and came back after each
removal. The program's consumer is now composed only for a module with
an account of its own and a process resource with no bus of its own;
the tool runner's twin stays for every consuming module.

Builds: design 47 H2 H-A-472 addendum and second addendum, G A-397
2026-11-22 14:12:45 +01:00
jschoubben 9005a2ee8e Grants: the behind check leaves out an orphaned durable and names it apart
About 110 durables left by modules that moved into or out of the tool
runner pile up behind their stream's head and raised 'Messages pile up
for a listener' for no real backlog. A durable with no pulls waiting
whose twin on the stream (<node>_<module> and <node>_<module>_tools) has
pulls waiting and delivered within the day is now left out of that check
and named once in mesh-grants.durable-orphaned, cleared when gone.

Builds: design 47 H2 H-A-472 (2), G A-340
2026-11-22 14:03:55 +01:00
jschoubben b914974b1d Judge test: the unknown top-level word is one no SDK knows
The row proving that the judgement's strict read refuses an unknown
top-level word used class, which the H2 SDK knows, so it failed at main.
It now uses a word no SDK knows and proves the same refusal.

Builds: design 47 H2 H-A-465, H-A-469
2026-11-22 13:57:22 +01:00
317 changed files with 14246 additions and 8138 deletions
@@ -0,0 +1,152 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/buscalls"
)
// assignmentDropTool drops one assignment key of a module no manifest names any more by hand (design 47 H2 H-A-509): a
// module key `<node>.<module>` of a retired module, as the clean state of the pass drops it, the act written in the
// hand-act log first.
const assignmentDropTool = "assigner_assignment_drop"
// assignmentLeft is why a module key `<node>.<module>` is not dropped, "" when it may be (H-A-509 and its second
// addendum, and the lead's answer of review round 1): only when no watched branch's catalog half holds the module (trunk, as
// world.trunk is) and the node key does not name it, since the node key is the commit of a write and a hand act never leaves
// one node's keys disagreeing; nothing while no half holds any module.
func assignmentLeft(node, module string, trunk map[string]bool, nodeRaw []byte, nodeFound bool) string {
switch {
case len(trunk) == 0:
return "no watched branch's catalog half holds a module yet, so no module is known to be retired"
case trunk[module]:
return "a watched branch's catalog half holds " + module
case !nodeFound:
return ""
}
n, err := mmac.DecodeNode(nodeRaw)
if err != nil {
return fmt.Sprintf("the node key of %s does not read, so whether it names %s is not known: %v", node, module, err)
}
if slices.ContainsFunc(n.Modules, func(r mma.AssignmentsByNodeNodeValueModulesItem) bool { return r.Module == module }) {
return "the node key of " + node + " still names " + module + ", so it stays placed there"
}
return ""
}
// dropAssignment deletes the module key of module on node, the act first recorded through the seat mesh-hand-acts; trunk
// answers every module a watched branch's catalog half holds.
func dropAssignment(st seatStore, ask func(string, any) (json.RawMessage, error), trunk func() (map[string]bool, error), node, module, why, by string) (any, error) {
switch {
case node == "" || module == "":
return nil, errors.New("name the node and the module whose assignment key is dropped")
case why == "":
return nil, errors.New("an assignment key dropped by hand says why")
case by == "" || by == stdio.Unproven:
return nil, errors.New("an assignment key dropped by hand names who drops it, and the runtime proved no caller")
}
key, err := mmac.ModuleKey(node, module)
if err != nil {
return nil, err
}
nodeKey, err := mmac.NodeKey(node)
if err != nil {
return nil, err
}
raw, _, found, err := st.get(mma.StateAssignments, key)
if err != nil {
return nil, err
}
if !found {
return nil, fmt.Errorf("the assigner holds no assignment key %s", key)
}
modules, err := trunk()
if err != nil {
return nil, fmt.Errorf("the watched branches' modules cannot be read, so %s stays: %w", key, err)
}
nodeRaw, _, nodeFound, err := st.get(mma.StateAssignments, nodeKey)
if err != nil {
return nil, err
}
if left := assignmentLeft(node, module, modules, nodeRaw, nodeFound); left != "" {
return nil, fmt.Errorf("the assignment key %s stays: %s", key, left)
}
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: assignmentDropTool + " " + key, Why: why + " (" + by + ")", Cause: "assignment-drop"})
if err != nil {
return nil, fmt.Errorf("the drop of %s is not recorded, so the key stays: %w", key, err)
}
if err := st.del(mma.StateAssignments, key); err != nil {
return nil, fmt.Errorf("the assignment key %s is not dropped: %w", key, err)
}
return map[string]any{"key": key, "dropped": json.RawMessage(raw), "by": by, "hand-act": taken.Log}, nil
}
// watchedModules is every module any watched branch's catalog half holds, as the pass's world.trunk is (design 47 H2 H-A-509,
// the lead's answer of review round 1): the watched branches of the seat mesh-catalog's registrations, each branch's revision
// read whole through the verb revision, page by page; a branch with none yet holds none.
func watchedModules(call mcc.Call) func() (map[string]bool, error) {
return func() (map[string]bool, error) {
raw, err := call(mcc.RegistrationsVerb, meshcatalog.RegistrationsInput{})
if err != nil {
return nil, err
}
answer, said, ok := buscalls.Unwrap(raw)
if !ok {
return nil, fmt.Errorf("%s answered: %s", mcc.RegistrationsVerb, said)
}
var regs meshcatalog.RegistrationsAnswer
if err := json.Unmarshal(answer, &regs); err != nil || regs.Registrations == nil {
return nil, fmt.Errorf("%s answered no registrations: %v", mcc.RegistrationsVerb, err)
}
branches := map[string]bool{}
for _, reg := range regs.Registrations {
for _, b := range reg.Branches {
branches[b] = true
}
}
out := map[string]bool{}
for _, branch := range slices.Sorted(maps.Keys(branches)) {
for after := ""; ; {
a, err := askCandidatePage(call, meshcatalog.RevisionInput{Branch: branch, After: after})
if err != nil {
return nil, fmt.Errorf("the catalog half of %s cannot be read: %w", branch, err)
}
if a.NoneYet {
break
}
for _, e := range a.Entries {
out[e.Module] = true
}
if a.Next == "" {
break
}
after = a.Next
}
}
return out, nil
}
}
// assignmentDropTools is the tool over the runtime's states.
func assignmentDropTools(st seatStore, ask func(string, any) (json.RawMessage, error), trunk func() (map[string]bool, error)) []stdio.Tool {
return []stdio.Tool{{Name: assignmentDropTool, Description: "Drop one assignment key by hand (design 47 H2 H-A-509): the module " +
"key <node>.<module> of the seat mesh-module-assigner's assignments, for a module no watched branch's catalog half holds any more " +
"(a retired module's key, which may predate the value's version), as the clean state of the pass drops it. Refused while a " +
"watched branch's catalog half holds the module, while the node key <node>.node still names it, or with no key there. Recorded as a " +
"hand act first.",
Input: schema(map[string]string{"node": "the node's name", "module": "the module's name", "why": "why the key is dropped"},
[]string{"node", "module", "why"}),
Run: func(a map[string]any) (any, error) {
return dropAssignment(st, ask, trunk, arg(a, "node"), arg(a, "module"), arg(a, "why"), stdio.CallerOf(a))
}}}
}
@@ -0,0 +1,175 @@
package main
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
plc "mesh-delivery-assigner/internal/assignment"
)
// H-A-509 and its second addendum: a module key of a module no manifest of the trunk names, that the node key does not name,
// is dropped, by hand through assigner_assignment_drop (recorded as a hand act first) and at the pass's clean state (named in
// the journal); a key a manifest of the trunk still names, or the node key still names, stays; nothing goes while the trunk
// is empty.
func TestARetiredModulesAssignmentKeyIsDropped(t *testing.T) {
// novox places web; the key of the retired checker predates the value's version; the key of the retired old is still
// named by the node key.
values, err := mmac.AssignmentsValues(mma.Assignments{V: mmac.Version, Node: "novox", Modules: []mma.PlacedModule{{Module: "web"}, {Module: "old"}}})
if err != nil {
t.Fatal(err)
}
values["novox.checker"] = []byte(`{"node":"novox"}`)
checker, web, old := "novox.checker", "novox.web", "novox.old"
trunkOf := func(names ...string) map[string]bool {
out := map[string]bool{}
for _, n := range names {
out[n] = true
}
return out
}
copyOf := func() map[string][]byte {
out := map[string][]byte{}
for k, v := range values {
out[k] = v
}
return out
}
t.Run("by hand", func(t *testing.T) {
for _, c := range []struct {
name, module string
trunk map[string]bool
refuse error
dropped bool
}{
{"a retired module's key", "checker", trunkOf("web"), nil, true},
{"a manifest of the trunk names it", "web", trunkOf("web"), nil, false},
{"the node key still names it", "old", trunkOf("web"), nil, false},
{"the trunk is empty", "checker", trunkOf(), nil, false},
{"no key there", "gone", trunkOf("web"), nil, false},
{"not recorded", "checker", trunkOf("web"), errors.New("no responders"), false},
} {
st := memStore{mma.StateAssignments: &memKV{values: copyOf()}}
var asked []string
ask := func(verb string, body any) (json.RawMessage, error) {
raw, _ := json.Marshal(body)
asked = append(asked, verb+" "+string(raw))
return json.RawMessage(`{}`), c.refuse
}
trunk := func() (map[string]bool, error) { return c.trunk, nil }
out, err := dropAssignment(st, ask, trunk, "novox", c.module, "retired", "person.jochen")
key := "novox." + c.module
_, there := st[mma.StateAssignments].values[key]
switch {
case c.dropped && (err != nil || there || len(asked) != 1 || !strings.Contains(asked[0], assignmentDropTool+" "+key)):
t.Errorf("%s: %v, %v; the key left %v, asked %v", c.name, out, err, there, asked)
case !c.dropped && err == nil:
t.Errorf("%s: %v, want it refused", c.name, out)
case len(st[mma.StateAssignments].values) != len(values)-btoi(c.dropped):
t.Errorf("%s: %d keys left, want %d", c.name, len(st[mma.StateAssignments].values), len(values)-btoi(c.dropped))
}
}
if _, err := dropAssignment(memStore{mma.StateAssignments: &memKV{values: copyOf()}}, nil, func() (map[string]bool, error) { return trunkOf("web"), nil },
"novox", "checker", "", "person.jochen"); err == nil {
t.Error("a drop with no why is not refused")
}
})
// The tool judges against every watched branch's half, as the pass does (the lead's answer of review round 1): the branches
// of the registrations, each read page by page; a branch with none yet holds none.
t.Run("every watched branch", func(t *testing.T) {
call := func(verb string, body any) (json.RawMessage, error) {
switch verb {
case meshcatalogclient.RegistrationsVerb:
return json.Marshal(meshcatalog.RegistrationsAnswer{Registrations: []meshcatalog.Registration{{Module: "web", Branches: []string{"main", "feature"}}, {Module: "db", Branches: []string{"fresh"}}}})
case meshcatalogclient.RevisionVerb:
in := body.(meshcatalog.RevisionInput)
switch {
case in.Branch == "main" && in.After == "":
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "web"}}, Next: "web"})
case in.Branch == "main":
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "db"}}})
case in.Branch == "feature":
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "new"}}})
}
return json.Marshal(meshcatalog.RevisionAnswer{NoneYet: true})
}
return nil, errors.New("no such verb " + verb)
}
got, err := watchedModules(call)()
if err != nil || len(got) != 3 || !got["web"] || !got["db"] || !got["new"] {
t.Errorf("watchedModules = %v, %v; want web, db and new", got, err)
}
})
t.Run("at the pass", func(t *testing.T) {
for _, c := range []struct {
name string
trunk []string
gone []string
}{
{"a retired module's key goes, one the node key names stays", []string{"web"}, []string{checker}},
{"the trunk is empty", nil, nil},
} {
kv := &memKV{values: copyOf()}
p := newPasser(kvSet{plc.AssignmentsBucket(): kv}, time.Now())
var said []string
p.logf = func(f string, a ...any) { said = append(said, f) }
for k, v := range kv.values {
p.w.put(plc.AssignmentsBucket(), k, v)
}
// web is held by a watched branch that is not the trunk's first: the pass judges against every watched branch's half.
for _, n := range c.trunk {
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fpTest, Repository: "novox/" + n, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, "feature", n, mod)
}
for range 2 {
p.wants(context.Background())
}
for _, key := range []string{checker, web, old, "novox.node"} {
_, there := kv.values[key]
if want := !contains(c.gone, key); there != want {
t.Errorf("%s: %s left = %v, want %v", c.name, key, there, want)
}
}
if dropped, left := countSaid(said, "is dropped"), countSaid(said, "is left"); len(c.gone) > 0 && (dropped != 1 || left != 1) {
t.Errorf("%s: said dropped %d and left %d times, want once each: %v", c.name, dropped, left, said)
}
}
})
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func contains(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
func countSaid(said []string, words string) int {
n := 0
for _, s := range said {
if strings.Contains(s, words) {
n++
}
}
return n
}
@@ -154,6 +154,13 @@ func (b *builtEnds) madeOf(module, fp string) map[string]string {
return parts return parts
} }
// releasedOf is the version released of module's done build at fp, the release whose parts are what its build.ended made (design
// 47 G A-421); false when no such release is heard.
func (w *world) releasedOf(module, fp string) (string, bool) {
k, ok := w.released.withParts(module, w.ends.madeOf(module, fp))
return k.Version, ok && k.Version != ""
}
// of is the version of module released from the source revision, with its parts' digests; false before it is heard. // of is the version of module released from the source revision, with its parts' digests; false before it is heard.
func (r *releasedVersions) of(module string, source int64) (assign.KeptBuild, bool) { func (r *releasedVersions) of(module string, source int64) (assign.KeptBuild, bool) {
r.mu.Lock() r.mu.Lock()
@@ -44,7 +44,12 @@ func dropOver(call func(key string, body any) (json.RawMessage, error)) func(ask
} }
} }
// waitOf is a reader's wait for a build node to take its run's ask (A-469y). // waitOnPublish begins what a composition run's waiting reader waits on while the run waits for a package's publish, the
// package's path after it (design 47 H2 H-A-630 (5)).
const waitOnPublish = "publish of package "
// waitOf is a reader's wait for a build node to take its run's ask (A-469y); while the run's value holds `waits`, its wait for
// that package's publish before the ask is put, naming the package and the entry, never a build node (H-A-630 (5)).
func waitOf(run meshwants.CompositionRun, reader meshwants.CompositionReader) meshwants.Wait { func waitOf(run meshwants.CompositionRun, reader meshwants.CompositionReader) meshwants.Wait {
w := meshwants.Wait{Step: "pipeline", Owner: meshwants.Seat, Module: reader.Module, Node: run.Machine, On: waitOnBuildNode, Fp: reader.Fingerprint, w := meshwants.Wait{Step: "pipeline", Owner: meshwants.Seat, Module: reader.Module, Node: run.Machine, On: waitOnBuildNode, Fp: reader.Fingerprint,
Words: fmt.Sprintf("the composition step of %s waits for a build node to take the composition run %s of %s (ask %s)", reader.Pipeline, Words: fmt.Sprintf("the composition step of %s waits for a build node to take the composition run %s of %s (ask %s)", reader.Pipeline,
@@ -52,17 +57,38 @@ func waitOf(run meshwants.CompositionRun, reader meshwants.CompositionReader) me
if run.Started != nil { if run.Started != nil {
w.Since = *run.Started w.Since = *run.Started
} }
if run.Waits != nil {
w.On, w.Since = waitOnPublish+run.Waits.Package, run.Waits.Since
w.Words = fmt.Sprintf("the composition step of %s waits for the publish of package %s, named with no version in %s, before the composition run %s of %s is asked (ask %s)",
reader.Pipeline, run.Waits.Package, run.Waits.Entry, runKeyOf(run.Candidate, run.Machine), run.Machine, run.Ask)
}
return w return w
} }
// sayWaits says, for each reader, its wait held or ended (how: ran, superseded); a wait that cannot be said is journaled. // sayWaits says, for each reader, its wait held or ended (how: ran, superseded); a wait that cannot be said is journaled.
func (r *compositionRuns) sayWaits(run meshwants.CompositionRun, readers []meshwants.CompositionReader, how string) { func (r *compositionRuns) sayWaits(run meshwants.CompositionRun, readers []meshwants.CompositionReader, how string) {
r.sayWaitsOf(run, readers, how, "")
}
// sayWaitsAtPut says, at the put of the run ask of a run whose wait for a package's publish ended, its readers' wait-held for a
// build node again, under their held id with .put added, so the bus's duplicate window does not take it for the first one's
// (design 47 H2 H-A-632).
func (r *compositionRuns) sayWaitsAtPut(run meshwants.CompositionRun) {
r.sayWaitsOf(run, run.Readers, "", ".put")
}
// sayWaitsOf is sayWaits, each held id with after added.
func (r *compositionRuns) sayWaitsOf(run meshwants.CompositionRun, readers []meshwants.CompositionReader, how, after string) {
if r.say == nil { if r.say == nil {
return return
} }
for _, c := range readers { for _, c := range readers {
w := waitOf(run, c) w := waitOf(run, c)
event, id := meshwants.EventWaitHeld, "composition."+runKeyOf(run.Candidate, run.Machine)+"."+run.Ask+"."+c.ID+".held" event, id := meshwants.EventWaitHeld, "composition."+runKeyOf(run.Candidate, run.Machine)+"."+run.Ask+"."+c.ID+".held"
if run.Waits != nil && how == "" { // a wait-held of its own, so the bus's duplicate window does not take it for the first one's
id += "." + run.Waits.Package
}
id += after
if how != "" { if how != "" {
w.How, event, id = how, meshwants.EventWaitEnded, strings.TrimSuffix(id, ".held")+".ended" w.How, event, id = how, meshwants.EventWaitEnded, strings.TrimSuffix(id, ".held")+".ended"
} }
@@ -193,6 +219,10 @@ func (r *compositionRuns) expired(boundKey string) {
if err != nil || !ok || run.Ended != nil { if err != nil || !ok || run.Ended != nil {
return return
} }
if setting == "composition-step-bound" && run.Waits != nil { // the bound a wait for a package's publish armed (H-A-628 (4))
r.waitExpired(boundKey, key, run)
return
}
// The marker of an expiry holds no value (A-470o): the run ends only while its bound is still absent when read again, and // The marker of an expiry holds no value (A-470o): the run ends only while its bound is still absent when read again, and
// the run is taken for bound., untaken for untaken., so an expiry heard after a bound was armed again, or of a run replaced // the run is taken for bound., untaken for untaken., so an expiry heard after a bound was armed again, or of a run replaced
// since, ends nothing. // since, ends nothing.
@@ -229,6 +259,25 @@ func (r *compositionRuns) expired(boundKey string) {
} }
} }
// waitExpired ends a run whose wait for a package's publish passed its bound, the expiry of the bound key bound.<run key> the
// wait armed (design 47 H2 H-A-628 (3), (4)): could not run naming the package, the entry and the bound, read from the run's value
// (H-A-629 (1), H-A-631). Its run ask is not put yet, so none is dropped; a bound armed again since (the marker holds no value,
// A-470o) ends nothing.
func (r *compositionRuns) waitExpired(boundKey, key string, run meshwants.CompositionRun) {
_, _, armed, err := r.boundOf(boundKey)
if err != nil {
r.logf("the bound %s is not read again, so its expiry ends nothing: %v", boundKey, err)
return
}
if armed {
r.logf("the expiry of %s ends nothing: the bound is armed again (A-470o)", boundKey)
return
}
if _, err := r.endRun(key, run.Ask, meshwants.CompositionRunOutcomeCouldNotRun, r.pastWaitSaid(run.Machine, *run.Waits), nil); err != nil {
r.logf("the composition run %s past its wait for package %s is not ended: %v", key, run.Waits.Package, err)
}
}
// endRun ends a run (end) and clears its bounds: the untaken key's readers said superseded, both bound keys deleted. // endRun ends a run (end) and clears its bounds: the untaken key's readers said superseded, both bound keys deleted.
func (r *compositionRuns) endRun(key, ask, outcome, said string, verdict map[string]any) (bool, error) { func (r *compositionRuns) endRun(key, ask, outcome, said string, verdict map[string]any) (bool, error) {
return r.endRunOf(key, ask, outcome, said, verdict, r.untaken(key, ask)) return r.endRunOf(key, ask, outcome, said, verdict, r.untaken(key, ask))
@@ -17,6 +17,7 @@ import (
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -46,6 +47,9 @@ const (
// entryVerbKey and seatDefinitionsKey are the mesh-catalog seat verbs the step reads. // entryVerbKey and seatDefinitionsKey are the mesh-catalog seat verbs the step reads.
entryVerbKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbEntry entryVerbKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbEntry
seatDefinitionsKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbSeatDefinitions seatDefinitionsKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbSeatDefinitions
// publishedVerbKey is the build seat's read of whether a package built at a fingerprint is published, what fills a run's
// empty pin (design 47 H-A-328, H2 H-A-628 (2)).
publishedVerbKey = "seat:" + builds.Seat + "." + builds.VerbPublished
) )
// compositionRun runs a composition step. // compositionRun runs a composition step.
@@ -80,6 +84,9 @@ type compositionRun struct {
away func(machine string) bool away func(machine string) bool
// put puts a run ask on the build seat's check queue under the assigner's name. // put puts a run ask on the build seat's check queue under the assigner's name.
put func(ctx context.Context, a buildstep.StepAsk) error put func(ctx context.Context, a buildstep.StepAsk) error
// own is the assigner's own context: a run's start, and its wait for a package's publish, run on it as the take-up's do, never
// on the starting step's, which a supersede or a drop ends while other steps share the run (design 47 H2 H-A-630 (3)).
own context.Context
// reads shares the catalog reads among steps (compositionreads.go); sleep waits between two tries of a read (nil: a timer). // reads shares the catalog reads among steps (compositionreads.go); sleep waits between two tries of a read (nil: a timer).
reads *compositionReads reads *compositionReads
sleep func(ctx context.Context, d time.Duration) error sleep func(ctx context.Context, d time.Duration) error
@@ -130,7 +137,7 @@ func (r *compositionRun) run(ctx context.Context, id string, step meshwants.Step
continue continue
} }
if j.started { if j.started {
go r.start(ctx, j.key, j.run, prep, id) go r.start(r.own, j.key, j.run, prep, id) // on the assigner's own context (H-A-630 (3))
} }
keys = append(keys, j.key) keys = append(keys, j.key)
} }
@@ -138,11 +145,10 @@ func (r *compositionRun) run(ctx context.Context, id string, step meshwants.Step
} }
// read waits for the end of each run of keys and judges the step of module from them, naming in its progress and its end the // read waits for the end of each run of keys and judges the step of module from them, naming in its progress and its end the
// runs it reads and their asks (§723, §729). // runs it reads and their asks (§723, §729); while a run it reads waits for a package's publish its phase is fetch (H-A-629 (2)).
func (r *compositionRun) read(ctx context.Context, module string, keys []string, ends []machineEnd) stepOutcome { func (r *compositionRun) read(ctx context.Context, module string, keys []string, ends []machineEnd) stepOutcome {
setShared(ctx, r.runs.sharedOf(keys, nil)) setShared(ctx, r.runs.sharedOf(keys, nil))
setPhase(ctx, meshwants.StepProgressEventPhaseRun) runs := r.runs.awaitEach(ctx, keys, r.sayingWaits(ctx, "the composition step of "+module))
runs := r.runs.await(ctx, keys)
setPhase(ctx, meshwants.StepProgressEventPhaseReport) setPhase(ctx, meshwants.StepProgressEventPhaseReport)
for _, key := range keys { for _, key := range keys {
ends = append(ends, judgeRun(module, runs[key])) ends = append(ends, judgeRun(module, runs[key]))
@@ -221,7 +227,10 @@ type runPrep struct {
manifests map[string]composer.Manifest manifests map[string]composer.Manifest
none map[string]string none map[string]string
programOf func(node string) (buildstep.RunProgram, string, map[string]string, error) programOf func(node string) (buildstep.RunProgram, string, map[string]string, error)
err error // publishers are the publishers of each package in the step's catalog revision, what an empty pin is filled from
// (H-A-628 (2)).
publishers map[string]packagePublisher
err error
} }
func (p *runPrep) get(ctx context.Context) error { func (p *runPrep) get(ctx context.Context) error {
@@ -231,6 +240,7 @@ func (p *runPrep) get(ctx context.Context) error {
p.err = errors.New("the step's catalog revision is not read: " + err.Error()) p.err = errors.New("the step's catalog revision is not read: " + err.Error())
return return
} }
p.publishers = publishersOf(half.Entries) // the step's own revision, before any branch's entry is laid over it
if p.r.newest != nil && p.r.watched != nil { if p.r.newest != nil && p.r.watched != nil {
half = acrossBranches(p.step, half, p.r.newest(), p.r.watched) half = acrossBranches(p.step, half, p.r.newest(), p.r.watched)
} }
@@ -283,6 +293,13 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
end(node + ": " + err.Error()) end(node + ": " + err.Error())
return return
} }
pins, said, ok := r.awaitPins(ctx, key, ask, "the node-engine's entry "+engineFp, pins, prep.publishers)
if !ok {
if said != "" { // else the run ended or was replaced while it waited, or the step's wait ended
end(node + ": " + said)
}
return
}
cs := composer.Case{Name: changeCase, Manifests: prep.manifests, None: prep.none} cs := composer.Case{Name: changeCase, Manifests: prep.manifests, None: prep.none}
if left, err := r.leftOut(node, unlisted); err != nil { if left, err := r.leftOut(node, unlisted); err != nil {
end(node + ": " + err.Error()) end(node + ": " + err.Error())
@@ -309,20 +326,27 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
end(node + ": " + err.Error()) end(node + ": " + err.Error())
return return
} }
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool { waited := false
written, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
waited = false
if c.Ask != ask || c.Ended != nil { if c.Ask != ask || c.Ended != nil {
return false return false
} }
c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: engineFp} c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: engineFp}
c.Input = digest c.Input = digest
waited, c.Waits = c.Waits != nil, nil // its wait ends as its run ask is put (H-A-629 (1))
return true return true
}); err != nil { })
if err != nil {
end(node + ": the run's program and input are not written: " + err.Error()) end(node + ": the run's program and input are not written: " + err.Error())
return return
} }
if waited { // its readers wait for a build node again, no longer for the package's publish (H-A-632)
r.runs.sayWaitsAtPut(written)
}
a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(), a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(),
Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the composition of " + node + " by the node-engine at " + program.Commit}, Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the composition of " + node + " by the node-engine at " + program.Commit},
Packages: pins} // the composer is built against its entry's pins, as every build (H-A-203, H-A-192) Packages: pins} // the composer is built against its entry's pins, each empty one filled (H-A-203, H-A-192, H-A-628 (2))
if err := r.put(ctx, a); err != nil { if err := r.put(ctx, a); err != nil {
end(node + ": its run ask " + ask + " is not put: " + err.Error()) end(node + ": its run ask " + ask + " is not put: " + err.Error())
} }
@@ -737,22 +761,260 @@ func programOfEntry(e meshcatalog.CatalogEntry) (buildstep.RunProgram, error) {
return buildstep.RunProgram{Repository: e.Repository, Commit: e.Commit, Dir: dir, Package: composer.Package}, nil return buildstep.RunProgram{Repository: e.Repository, Commit: e.Commit, Dir: dir, Package: composer.Package}, nil
} }
// pinsOfEntry are the mesh packages' versions an entry pins, the ones it names with a version (H-A-203, H-A-183): the pins // pinsOfEntry are the mesh packages' versions an entry names (H-A-203, H-A-183, H-A-204): the pins a run's program is built
// a run's program is built against, in the form the entry keeps and the builder sends. nil when it pins none. // against, in the form the entry keeps and the builder sends, a package it names with no version kept with an empty one,
// never left out, for filledPins to fill (H-A-628 (5)). nil when it names none.
func pinsOfEntry(e meshcatalog.CatalogEntry) map[string]string { func pinsOfEntry(e meshcatalog.CatalogEntry) map[string]string {
var out map[string]string if len(e.Packages) == 0 {
for path, version := range e.Packages { return nil
if version == "" { }
continue return maps.Clone(e.Packages)
}
// packagePublisher is the build of a catalog revision that publishes a package: its module, the package's artifact reference
// (<module>:<artifact>) and the build's fingerprint, what the seat mesh-builds' published is asked of (H-A-328, H-A-628 (2)).
type packagePublisher struct {
module, artifact, fingerprint string
}
// publishersOf are the publishers of each package the entries of a catalog revision publish, by package name.
func publishersOf(entries map[string]meshcatalog.CatalogEntry) map[string]packagePublisher {
out := map[string]packagePublisher{}
for _, e := range entries {
for _, a := range e.Artifacts {
if a.Package != nil && a.Package.Name != "" && e.Fp != "" {
out[a.Package.Name] = packagePublisher{module: e.Module, artifact: a.Ref, fingerprint: e.Fp}
}
} }
if out == nil {
out = map[string]string{}
}
out[path] = version
} }
return out return out
} }
// unpublished is a package an entry names with no version whose publisher's build in the step's revision is not published.
type unpublished struct {
path string
by packagePublisher
}
// unpublishedSaid names each package of waiting and the build it waits for.
func unpublishedSaid(waiting []unpublished) string {
var said []string
for _, u := range waiting {
said = append(said, fmt.Sprintf("package %s has no published version: the build of %s at %s (%s) is not published", u.path, u.by.module, u.by.fingerprint, u.by.artifact))
}
return strings.Join(said, "; ")
}
// filledPins fills each empty pin of pins, which the entry what names, from the seat mesh-builds' verb published, asked of the
// package's publisher in the step's catalog revision: the version it answers is the pin, never one the assigner computes
// (design 47 H2 H-A-628 (2), H-A-328, H-A-192). It answers the pins with every one it could fill, the packages whose
// publisher's build is not published yet, or an error naming the package, the entry and why it has no version (H-A-628 (5)).
// pins itself is left as it is: one entry's pins serve every machine's run.
func (r *compositionRun) filledPins(ctx context.Context, what string, pins map[string]string, publishers map[string]packagePublisher) (map[string]string, []unpublished, error) {
pins = maps.Clone(pins)
var waiting []unpublished
for _, path := range slices.Sorted(maps.Keys(pins)) {
if pins[path] != "" {
continue
}
by, ok := publishers[path]
if !ok {
return nil, nil, fmt.Errorf("package %s has no version in %s, and no build of the step's catalog revision publishes it", path, what)
}
v, published, err := r.publishedOf(ctx, by)
if err != nil {
return nil, nil, fmt.Errorf("package %s has no version in %s, and whether the build of %s at %s publishes it is not read: %w", path, what, by.module, by.fingerprint, err)
}
if !published {
waiting = append(waiting, unpublished{path: path, by: by})
continue
}
pins[path] = v
r.logf("package %s, named with no version in %s, is pinned at %s: the build of %s at %s published it (mesh-builds' published, H-A-628)", path, what, v, by.module, by.fingerprint)
}
return pins, waiting, nil
}
// awaitPins fills the empty pins of the entry what names for the run of ask under key (filledPins) and, while a package's
// publisher's build is not published, waits for it (design 47 H2 H-A-628 (3), (4); H-A-629 (1), (3)): the run's value names the
// package in `waits`, the time its wait began kept across a start taken up again; the run's bound key bound.<run key> is armed
// for what is left of package-wait-minutes from that time, never in full again; published is read first and again at each
// package-published heard (H-A-326), and the run's end is heard through its own state, its bound's expiry among them. It answers
// the pins, every one filled, the bound key deleted again (an ask in the queue has no clock, §720), and true; else false and why the
// run could not run, or no words when the run ended or was replaced meanwhile, or ctx ended.
func (r *compositionRun) awaitPins(ctx context.Context, key, ask, what string, pins map[string]string, publishers map[string]packagePublisher) (map[string]string, string, bool) {
armed, said := false, ""
for {
// The wake of each empty pin's publisher, taken before the read, so a publish heard meanwhile wakes the next one; the run
// waits on the one of the package its `waits` names alone (H-A-630 (1)).
wakes := map[string]<-chan struct{}{}
for path, v := range pins {
if by, ok := publishers[path]; ok && v == "" {
wakes[path] = r.runs.publishWake(by.artifact)
}
}
filled, waiting, err := r.filledPins(ctx, what, pins, publishers)
if err != nil {
return nil, err.Error(), false
}
if len(waiting) == 0 {
if armed {
if err := r.runs.clearBounds(key, ask, runBoundPrefix); err != nil {
r.logf("the bound of the composition run %s's wait is not deleted: %v", key, err)
}
r.logf("the composition run %s waits no more: every package %s names is published", key, what)
}
return filled, "", true
}
path := waiting[0].path
published := wakes[path]
since, held, err := r.runs.waitFor(key, ask, path, what)
if err != nil {
return nil, "its wait for package " + path + " is not written: " + err.Error(), false
}
if !held {
return nil, "", false
}
left := since.Add(r.runs.set.packageWait).Sub(r.now())
if left <= 0 {
return nil, r.runs.pastWaitSaid("", meshwants.CompositionRunWaits{Package: path, Entry: what}), false
}
if !armed {
stands, err := r.runs.armBound(runBoundPrefix, key, ask, wholeSeconds(left))
if err != nil {
return nil, "the bound of its wait for package " + path + " is not armed: " + err.Error(), false
}
if !stands {
return nil, "", false
}
armed = true
}
if path != said {
said = path
r.logf("the composition run %s waits for package %s, named with no version in %s: %s; %s ends its wait at %s", key, path, what,
unpublishedSaid(waiting), packageWaitSetting, since.Add(r.runs.set.packageWait).Format(time.RFC3339))
// Its readers are said waiting for that package's publish, naming it, no longer for a build node (H-A-630 (5)).
if run, _, ok, err := r.runs.read(key); err == nil && ok && run.Ended == nil && run.Ask == ask && run.Waits != nil {
r.runs.sayWaits(run, run.Readers, "")
}
}
for woke := false; !woke; {
changed := r.runs.wake()
run, _, ok, err := r.runs.read(key)
if err == nil && (!ok || run.Ended != nil || run.Ask != ask) {
return nil, "", false
}
select {
case <-ctx.Done():
return nil, "", false
case <-published:
woke = true
case <-changed:
}
}
}
}
// wholeSeconds is d rounded up to a whole second, the bus's least step of a key's time to live: what is left of a wait's bound
// is never refused as a time to live below a second.
func wholeSeconds(d time.Duration) time.Duration {
if w := d.Truncate(time.Second); w < d {
return w + time.Second
}
return d
}
// sayingWaits is what a step reading runs says of them at each read (design 47 H2 H-A-629 (2)): the phase fetch while a run it
// reads holds `waits`, its journal naming the package, and run once none does.
func (r *compositionRun) sayingWaits(ctx context.Context, what string) func(map[string]meshwants.CompositionRun) {
said := ""
return func(runs map[string]meshwants.CompositionRun) {
waits, of := "", ""
for _, key := range slices.Sorted(maps.Keys(runs)) {
if run := runs[key]; run.Ended == nil && run.Waits != nil {
waits, of = run.Waits.Package, key
break
}
}
if waits == "" {
setPhase(ctx, meshwants.StepProgressEventPhaseRun)
} else {
setPhase(ctx, meshwants.StepProgressEventPhaseFetch)
}
if waits != said {
if waits != "" {
r.logf("%s says fetch: the composition run %s waits for package %s", what, of, waits)
} else {
r.logf("%s says run: no composition run it reads waits for a package", what)
}
said = waits
}
}
}
// takeUpWaits takes up, at the assigner's start, each run still waiting for a package's publish, its value holding `waits` and
// no program (design 47 H2 H-A-629 (3)): past the time its wait began plus package-wait-minutes it ends could not run naming the
// package; before it, its bound key is armed again for what is left and its whole start runs again, a compose-candidate ask of the
// node and its kept request, which reads published first, as its first reader's step.
func (r *compositionRun) takeUpWaits(ctx context.Context) {
all, err := r.runs.keys()
if err != nil {
r.logf("composition-runs: the runs standing at the start are not read, so no run waiting for a package is taken up: %v", err)
return
}
for _, key := range all {
if !isRunKey(key) {
continue
}
run, _, ok, err := r.runs.read(key)
if err != nil || !ok || run.Ended != nil || run.Waits == nil || run.Program != nil {
continue
}
left := run.Waits.Since.Add(r.runs.set.packageWait).Sub(r.now())
if left <= 0 {
if _, err := r.runs.endRun(key, run.Ask, meshwants.CompositionRunOutcomeCouldNotRun, r.runs.pastWaitSaid(run.Machine, *run.Waits), nil); err != nil {
r.logf("the composition run %s past its wait for package %s is not ended: %v", key, run.Waits.Package, err)
}
continue
}
if _, err := r.runs.armBound(runBoundPrefix, key, run.Ask, wholeSeconds(left)); err != nil {
r.logf("the bound of the composition run %s's wait is not armed again: %v", key, err)
}
if len(run.Readers) == 0 {
r.logf("the composition run %s waiting for package %s has no reader, so its start does not run again; its bound ends it", key, run.Waits.Package)
continue
}
first := run.Readers[0]
r.logf("the composition run %s, waiting for package %s since %s, is taken up again: its start runs again (H-A-629 (3))", key, run.Waits.Package,
run.Waits.Since.Format(time.RFC3339))
if isValidateRun(run) {
go r.startValidate(ctx, key, run, stepRunOf(first))
} else {
go r.start(ctx, key, run, &runPrep{r: r, step: stepRunOf(first)}, first.ID)
}
}
}
// publishedOf asks the seat mesh-builds' verb published whether by's build is published, answering the pin it is published at
// (vMAJOR.MINOR.PATCH, spec S9) when it is.
func (r *compositionRun) publishedOf(ctx context.Context, by packagePublisher) (string, bool, error) {
body, said, err := r.callRetry(ctx, publishedVerbKey, builds.PublishedInput{Module: by.module, Artifact: by.artifact, Fingerprint: by.fingerprint})
if err != nil || body == nil {
return "", false, unreadErr(builds.VerbPublished+" did not answer", err, said)
}
a, _, err := builds.DecodePublishedAnswer(body)
if err != nil {
return "", false, fmt.Errorf("%s answered what does not read: %w", builds.VerbPublished, err)
}
if !a.Published {
return "", false, nil
}
if a.Version == "" {
return "", false, fmt.Errorf("%s answered published with no version", builds.VerbPublished)
}
return "v" + a.Version, true, nil
}
// programs answers, per machine, the composer its run builds and the node-engine fingerprint it was chosen from (A-226, A-243, // programs answers, per machine, the composer its run builds and the node-engine fingerprint it was chosen from (A-226, A-243,
// A-252, §719): where the revision's node-engine entry differs from the trunk's, that build for every machine; else the build the // A-252, §719): where the revision's node-engine entry differs from the trunk's, that build for every machine; else the build the
// machine's node-engine runs, as its `running` says, its entry read through mesh-catalog's `entry`; a machine whose node-engine's // machine's node-engine runs, as its `running` says, its entry read through mesh-catalog's `entry`; a machine whose node-engine's
@@ -4,7 +4,9 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/process"
"github.com/nats-io/nats.go/jetstream"
"maps" "maps"
"slices" "slices"
"strings" "strings"
@@ -17,6 +19,7 @@ import (
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -48,10 +51,81 @@ type runStand struct {
listFault error listFault error
// verdict, when set, is the composer's verdict of a machine (by node), else the stand's own. // verdict, when set, is the composer's verdict of a machine (by node), else the stand's own.
verdict func(node string) (composer.Machine, bool) verdict func(node string) (composer.Machine, bool)
// publishedAt is the version mesh-builds' published answers for a build fingerprint, none (not published) when absent;
// published are the asks it was given (H-A-628 (2)).
publishedAt map[string]string
published []builds.PublishedInput
// noPublisher: the revision holds no build publishing x/go.
noPublisher bool
}
// logLines is a journal a test awaits lines of: each write wakes the waiter, no sleep stands in for it.
type logLines struct {
mu sync.Mutex
text []string
grew chan struct{}
}
func newLogLines() *logLines { return &logLines{grew: make(chan struct{})} }
func (l *logLines) logf(format string, a ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.text = append(l.text, fmt.Sprintf(format, a...))
close(l.grew)
l.grew = make(chan struct{})
}
// await returns once n lines hold words, and fails the test when they did not come within 10 s.
func (l *logLines) await(t *testing.T, words string, n int) {
t.Helper()
deadline := time.After(10 * time.Second)
for {
l.mu.Lock()
count, grew := 0, l.grew
for _, line := range l.text {
if strings.Contains(line, words) {
count++
}
}
text := strings.Join(l.text, "\n")
l.mu.Unlock()
if count >= n {
return
}
select {
case <-grew:
case <-deadline:
t.Fatalf("no %d lines %q in the journal within 10 s:\n%s", n, words, text)
}
}
}
// eventsOf is the assigner's hub as a test hands it events: each handler by its subject, each bind's hearer.
type eventsOf struct {
handle map[string]func(jetstream.Msg)
bound []func(time.Time)
}
func (h *eventsOf) Handle(subject string, f func(jetstream.Msg)) error {
h.handle[subject] = f
return nil
}
func (h *eventsOf) OnBound(f func(time.Time)) { h.bound = append(h.bound, f) }
// say hands the handler of subject the event ev, and fails the test when it is not acknowledged.
func (h *eventsOf) say(t *testing.T, subject string, ev any) {
t.Helper()
raw, _ := json.Marshal(ev)
m := &heardMsg{data: raw, subject: subject}
h.handle[subject](m)
if !m.acked {
t.Errorf("the event %s on %s is not acknowledged", raw, subject)
}
} }
func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *runStand { func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *runStand {
s := &runStand{asks: map[string]buildstep.StepAsk{}, requests: map[string]composer.Request{}} s := &runStand{asks: map[string]buildstep.StepAsk{}, requests: map[string]composer.Request{}, publishedAt: map[string]string{"src2:x1": "0.1.9"}}
engine := func(fp, commit string) meshcatalog.CatalogEntry { engine := func(fp, commit string) meshcatalog.CatalogEntry {
return meshcatalog.CatalogEntry{Module: "engine", Fp: fp, Repository: "novox/mesh-host", Commit: commit, Path: ".", Serves: []string{ne.Seat + ".composition"}, return meshcatalog.CatalogEntry{Module: "engine", Fp: fp, Repository: "novox/mesh-host", Commit: commit, Path: ".", Serves: []string{ne.Seat + ".composition"},
Manifest: map[string]any{"module": "engine"}, Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.25-" + fp, "git.novox.be/novox/x/go": ""}} Manifest: map[string]any{"module": "engine"}, Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.25-" + fp, "git.novox.be/novox/x/go": ""}}
@@ -65,7 +139,9 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
Entries: []meshcatalog.CatalogEntry{engine(revisionEngine, revisionCommit), {Module: "bad", Verdict: mcc.VerdictRefused, Inputs: &meshcatalog.EntryInputs{Problems: []string{"no seat x"}}, Entries: []meshcatalog.CatalogEntry{engine(revisionEngine, revisionCommit), {Module: "bad", Verdict: mcc.VerdictRefused, Inputs: &meshcatalog.EntryInputs{Problems: []string{"no seat x"}},
Manifest: map[string]any{"module": "bad"}}}, Next: "bad"}, Manifest: map[string]any{"module": "bad"}}}, Next: "bad"},
"bad": {Revision: &meshcatalog.CatalogRevision{Revision: 7}, Entries: []meshcatalog.CatalogEntry{{Module: "m", Verdict: mcc.VerdictAccepted, Manifest: map[string]any{"module": "m"}}, "bad": {Revision: &meshcatalog.CatalogRevision{Revision: 7}, Entries: []meshcatalog.CatalogEntry{{Module: "m", Verdict: mcc.VerdictAccepted, Manifest: map[string]any{"module": "m"}},
{Module: "lidarr", None: "builders disagree: node", Manifest: map[string]any{"module": "lidarr"}}}}, // no fingerprint (A-470j) {Module: "lidarr", None: "builders disagree: node", Manifest: map[string]any{"module": "lidarr"}}, // no fingerprint (A-470j)
// x publishes the package the node-engine names with no version (H-A-628 (2)); no manifest, so the case holds none of it.
{Module: "x", Fp: "src2:x1", Artifacts: []meshcatalog.Artifact{{Ref: "x:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "git.novox.be/novox/x/go"}}}}}},
} }
call := func(key string, body any) (json.RawMessage, error) { call := func(key string, body any) (json.RawMessage, error) {
raw, _ := json.Marshal(body) raw, _ := json.Marshal(body)
@@ -77,6 +153,9 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
return nil, errors.New("asked another revision") return nil, errors.New("asked another revision")
} }
page := pages[in.After] page := pages[in.After]
if s.noPublisher {
page.Entries = slices.DeleteFunc(slices.Clone(page.Entries), func(e meshcatalog.CatalogEntry) bool { return e.Module == "x" })
}
if s.noDefinitions && page.Revision != nil { if s.noDefinitions && page.Revision != nil {
rev := *page.Revision rev := *page.Revision
rev.Definitions = nil rev.Definitions = nil
@@ -101,6 +180,14 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
s.mu.Unlock() s.mu.Unlock()
commit := map[string]string{"src2:e1": commitE1, "src2:e2": commitE2}[in.Fingerprint] commit := map[string]string{"src2:e1": commitE1, "src2:e2": commitE2}[in.Fingerprint]
return json.Marshal(meshcatalog.EntryAnswer{Entry: engine(in.Fingerprint, commit)}) return json.Marshal(meshcatalog.EntryAnswer{Entry: engine(in.Fingerprint, commit)})
case publishedVerbKey:
var in builds.PublishedInput
_ = json.Unmarshal(raw, &in)
s.mu.Lock()
s.published = append(s.published, in)
v, ok := s.publishedAt[in.Fingerprint]
s.mu.Unlock()
return json.Marshal(builds.PublishedAnswer{Published: ok, Version: v})
} }
return nil, errors.New("no such verb " + key) return nil, errors.New("no such verb " + key)
} }
@@ -114,7 +201,7 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
s.runs = newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf) s.runs = newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf)
s.r = &compositionRun{runs: s.runs, s.r = &compositionRun{runs: s.runs,
inputs: &compositionInputs{machines: func(string, string) []string { return []string{"ace", "g14", "shanks"} }, callFile: engines, bound: time.Second}, inputs: &compositionInputs{machines: func(string, string) []string { return []string{"ace", "g14", "shanks"} }, callFile: engines, bound: time.Second},
keeper: keeper, reads: &compositionReads{}, call: call, away: away, now: time.Now, logf: t.Logf, keeper: keeper, reads: &compositionReads{}, call: call, away: away, own: context.Background(), now: time.Now, logf: t.Logf,
trunk: func() (mcc.Half, bool) { trunk: func() (mcc.Half, bool) {
return mcc.Half{Entries: map[string]meshcatalog.CatalogEntry{"engine": engine(trunkEngine, commitE1)}}, true return mcc.Half{Entries: map[string]meshcatalog.CatalogEntry{"engine": engine(trunkEngine, commitE1)}}, true
}, },
@@ -187,11 +274,203 @@ func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
if s.asks["g14"].Run.Program.Commit != commitE2 { if s.asks["g14"].Run.Program.Commit != commitE2 {
t.Errorf("g14's composer is built at %s, want the build its node-engine runs", s.asks["g14"].Run.Program.Commit) t.Errorf("g14's composer is built at %s, want the build its node-engine runs", s.asks["g14"].Run.Program.Commit)
} }
// Each composer is built against the pins of the node-engine entry it is built from, a pin with no version left out // Each composer is built against the pins of the node-engine entry it is built from (H-A-203, H-A-192); 1984/AC9: the one
// (H-A-203, H-A-192). // it names with no version is filled from mesh-builds' published of its publisher's build in the step's revision, at the
// version that answers, never left out (H-A-628 (2), (5)).
for node, fp := range map[string]string{"ace": "src2:e1", "g14": "src2:e2"} { for node, fp := range map[string]string{"ace": "src2:e1", "g14": "src2:e2"} {
if got := s.asks[node].Packages; len(got) != 1 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.25-"+fp { if got := s.asks[node].Packages; len(got) != 2 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.25-"+fp || got["git.novox.be/novox/x/go"] != "v0.1.9" {
t.Errorf("%s's composer is built against the pins %v; want its entry's", node, got) t.Errorf("%s's composer is built against the pins %v; want its entry's, x/go at v0.1.9 from published", node, got)
}
}
if len(s.published) == 0 || s.published[0] != (builds.PublishedInput{Module: "x", Artifact: "x:go", Fingerprint: "src2:x1"}) {
t.Errorf("published was asked %+v, want x's build of x:go at src2:x1 in the step's revision", s.published)
}
// 1984/AC9: no run ask is put with a pin left out: no build of the revision publishing x/go ends the run could not run at once,
// naming the package and the entry, never the builder (H-A-628 (5)).
for name, c := range map[string]struct {
stand func(*runStand)
said string
}{
"no publisher": {func(s *runStand) { s.publishedAt = nil; s.noPublisher = true }, "package git.novox.be/novox/x/go has no version in the node-engine's entry src2:e1, and no build of the step's catalog revision publishes it"},
} {
u := newRunStand(t, "src2:e1", "src2:e1", "d1")
c.stand(u)
if out := u.r.run(context.Background(), "ask-step", step); out.Outcome != meshwants.StepEndedOutcomeCouldNotRun || !strings.Contains(out.Said, c.said) ||
strings.Contains(out.Said, "the builder pins or waits") || len(u.asks) != 0 {
t.Errorf("%s: the step came to %+v with %d run asks put, want could not run saying %q and none put", name, out, len(u.asks), c.said)
}
}
// 1984/AC9; H-A-628 (3), (4); H-A-629 (1), (2): x's build not published yet: each run waits, its value naming x/go in `waits`
// with the time its wait began, its bound bound.<run key> armed for package-wait-minutes, the step saying fetch naming the
// package; at the publish heard each reads published again and puts its run ask with the pin, `waits` and the bound gone, the
// step saying run; past the bound each ends could not run naming the package and the bound, no run ask put. H-A-630 (2): a
// bind of the consumer, the publish said while it was not bound, wakes each to read it published. H-A-630 (3): the starting
// step superseded leaves the runs another step shares waiting, and that step reads them composed after the publish. H-A-630 (4),
// H-A-631: past the bound, by the bound's expiry or at a take-up, the words name the package, the entry and the bound.
for _, how := range []string{"published", "bind", "superseded", "past its bound", "past its bound at a take-up"} {
publish := !strings.HasPrefix(how, "past its bound")
u := newRunStand(t, "src2:e1", "src2:e1", "d1")
u.publishedAt = nil
journal := newLogLines()
u.r.logf = journal.logf
atPut := map[string]string{} // by run key: what stood of its wait as its run ask was put
put := u.r.put
u.r.put = func(ctx context.Context, a buildstep.StepAsk) error {
key, run, _ := u.runs.keyOfAsk(a.ID)
bound, _, _ := u.runs.kv.get(runBoundPrefix + key)
u.mu.Lock()
atPut[key] = fmt.Sprintf("waits %v, bound %s", run.Waits, bound)
u.mu.Unlock()
return put(ctx, a)
}
lastHeld := map[string]string{} // by machine: what its newest wait-held waits on, and its id
u.runs.say = func(event string, body any, id string) error {
w := body.(meshwants.Wait)
journal.logf("said %s on %s: %s (%s)", event, w.On, w.Words, id)
if event == meshwants.EventWaitHeld {
u.mu.Lock()
lastHeld[w.Node] = w.On + " (" + id + ")"
u.mu.Unlock()
}
return nil
}
phase := &stepPhase{}
done := make(chan stepOutcome, 1)
first, supersede := context.WithCancel(context.WithValue(context.Background(), phaseKey{}, phase))
defer supersede()
go func() { done <- u.r.run(first, "ask-step", step) }()
journal.await(t, "waits for package git.novox.be/novox/x/go, named with no version in the node-engine's entry src2:e", 2)
journal.await(t, "the composition step of m says fetch: the composition run", 1)
// H-A-630 (5): each reader's wait-held says it waits for x/go's publish, naming the package and the entry.
journal.await(t, "said wait-held on "+waitOnPublish+"git.novox.be/novox/x/go: the composition step of waits for the publish of package git.novox.be/novox/x/go, named with no version in the node-engine's entry src2:e", 2)
if got := phase.get(); got != meshwants.StepProgressEventPhaseFetch {
t.Errorf("waiting, the step says the phase %q, want fetch", got)
}
kv := u.runs.kv.(*runsMem)
var keys []string
all, _ := u.runs.keys()
for _, key := range all {
if isRunKey(key) {
keys = append(keys, key)
}
}
for _, key := range keys {
run, _, _, _ := u.runs.read(key)
kv.mu.Lock()
ttl := kv.ttl[runBoundPrefix+key]
kv.mu.Unlock()
if len(keys) != 2 || run.Waits == nil || run.Waits.Package != "git.novox.be/novox/x/go" || !strings.HasPrefix(run.Waits.Entry, "the node-engine's entry src2:e") ||
run.Waits.Since.IsZero() || ttl <= 9*time.Minute || ttl > 10*time.Minute {
t.Errorf("the waiting run %s of %v holds %+v, its bound %s; want x/go and its entry in waits and package-wait-minutes' bound", key, keys, run.Waits, ttl)
}
}
switch how {
case "past its bound":
for _, key := range keys {
kv.expire(runBoundPrefix + key)
u.runs.expired(runBoundPrefix + key)
}
case "past its bound at a take-up": // the wait began longer ago than package-wait-minutes, as if the assigner were down
for _, key := range keys {
if _, _, err := u.runs.change(key, func(c *meshwants.CompositionRun) bool { c.Waits.Since = c.Waits.Since.Add(-time.Hour); return true }); err != nil {
t.Fatal(err)
}
}
u.r.takeUpWaits(context.Background())
case "superseded":
second := make(chan stepOutcome, 1)
go func() {
second <- u.r.run(context.WithValue(context.Background(), phaseKey{}, &stepPhase{}), "ask-step-2", step)
}()
journal.await(t, "the composition step of m says fetch: the composition run", 2) // the second step reads the waiting runs
supersede()
<-done
for _, key := range keys {
if run, _, _, _ := u.runs.read(key); run.Ended != nil || run.Waits == nil || len(run.Readers) != 2 {
t.Errorf("the starting step superseded, the run %s holds ended %v, waits %+v, readers %d; want it waiting for its two readers", key, run.Ended, run.Waits, len(run.Readers))
}
}
done = second
u.mu.Lock()
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
u.mu.Unlock()
u.runs.heardPublished("x:go")
case "bind":
hub := &eventsOf{handle: map[string]func(jetstream.Msg){}}
if err := hearPublished(hub, u.runs, t.Logf); err != nil {
t.Fatal(err)
}
u.mu.Lock()
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
u.mu.Unlock()
for _, bound := range hub.bound {
bound(time.Now())
}
default:
// H-A-630 (1): a package-published of another package wakes no run waiting for x/go, so it asks no published; x's own
// wakes each.
hub := &eventsOf{handle: map[string]func(jetstream.Msg){}}
if err := hearPublished(hub, u.runs, t.Logf); err != nil {
t.Fatal(err)
}
u.mu.Lock()
asked := len(u.published)
u.mu.Unlock()
hub.say(t, builds.SubjectPackagePublished, builds.PackagePublished{Module: "y", Artifact: "y:go", Branch: "main", Source: 7, Version: "0.2.0", V: 1})
u.runs.mu.Lock()
_, open := u.runs.published["x:go"]
u.runs.mu.Unlock()
u.mu.Lock()
after := len(u.published)
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
u.mu.Unlock()
if !open || after != asked {
t.Errorf("a publish of y:go woke the runs waiting for x/go (their wake standing %v) or asked published %d times more", open, after-asked)
}
hub.say(t, builds.SubjectPackagePublished, builds.PackagePublished{Module: "x", Artifact: "x:go", Branch: "main", Source: 7, Version: "0.1.9", V: 1})
}
var out stepOutcome
select {
case out = <-done:
case <-time.After(10 * time.Second):
t.Fatalf("%s: the waiting step said no end", how)
}
journal.await(t, "the composition step of m says run", 1)
if !publish {
for _, key := range keys {
if run, _, _, _ := u.runs.read(key); run.Ended == nil || run.Waits != nil {
t.Errorf("%s: the run %s holds ended %v, waits %+v; want it ended and its wait gone", how, key, run.Ended, run.Waits)
}
}
for node, fp := range map[string]string{"ace": "src2:e1", "g14": "src2:e2"} {
if want := node + ": package git.novox.be/novox/x/go has no published version within 10m0s (package-wait-minutes), named with no version in the node-engine's entry " + fp; out.Outcome != meshwants.StepEndedOutcomeCouldNotRun ||
!strings.Contains(out.Said, want) || strings.Contains(out.Said, "the builder pins or waits") || len(u.asks) != 0 {
t.Errorf("%s: the step came to %+v with %d run asks put, want could not run saying %q", how, out, len(u.asks), want)
}
}
continue
}
if out.Outcome != meshwants.StepEndedOutcomeFailed || !strings.Contains(out.Said, "g14 does not compose") || len(u.asks) != 2 {
t.Errorf("after the publish the step came to %+v with %d run asks", out, len(u.asks))
}
for node, a := range u.asks {
if a.Packages["git.novox.be/novox/x/go"] != "v0.1.9" {
t.Errorf("after the publish %s's composer is built against %v, want x/go at v0.1.9", node, a.Packages)
}
}
// H-A-632: at the put each reader's newest wait-held is for a build node again, under its held id with .put added.
for _, node := range []string{"ace", "g14"} {
u.mu.Lock()
got := lastHeld[node]
u.mu.Unlock()
if !strings.HasPrefix(got, waitOnBuildNode+" (") || !strings.HasSuffix(got, ".held.put)") {
t.Errorf("%s: after the put the newest wait-held of %s waits on %s, want a build node under its held id with .put", how, node, got)
}
}
for _, key := range keys {
if got := atPut[key]; got != "waits <nil>, bound " {
t.Errorf("as the run ask of %s was put its wait stood: %s; want waits and the bound gone (§720: an ask in the queue has no clock)", key, got)
}
} }
} }
if req.Depth != composer.DepthCompose || req.BlameTries != 20 || len(req.Machines) != 1 || req.Machines[0] != "ace" || len(req.Cases) != 1 || req.Cases[0].Name != changeCase || if req.Depth != composer.DepthCompose || req.BlameTries != 20 || len(req.Machines) != 1 || req.Machines[0] != "ace" || len(req.Cases) != 1 || req.Cases[0].Name != changeCase ||
@@ -15,6 +15,7 @@ import (
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
meshbuilds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
@@ -60,16 +61,35 @@ type runSettings struct {
kept, stepBound, untaken time.Duration kept, stepBound, untaken time.Duration
// blameTries is blame-tries, carried in each run's request (§721). // blameTries is blame-tries, carried in each run's request (§721).
blameTries int blameTries int
// packageWait is package-wait-minutes: how long a run waits for the publish of a package its entry names with no version
// before it ends could not run naming the package, counted from the time its wait began (design 47 H2 H-A-628 (3), H-A-629 (3)).
packageWait time.Duration
} }
// defaultRunSettings are the settings' defaults, as the manifest gives them. // defaultRunSettings are the settings' defaults, as the manifest gives them.
var defaultRunSettings = runSettings{capBytes: 16 << 20, kept: 24 * time.Hour, stepBound: 30 * time.Minute, untaken: 24 * time.Hour, blameTries: 20} var defaultRunSettings = runSettings{capBytes: 16 << 20, kept: 24 * time.Hour, stepBound: 30 * time.Minute, untaken: 24 * time.Hour, blameTries: 20,
packageWait: 10 * time.Minute}
// packageWaitUnit is the unit of the setting package-wait-minutes, a minute; the whole test sets a shorter one, so a run's wait
// passes its bound within the test (as tierBoundUnit).
var packageWaitUnit = time.Minute
// packageWaitSetting names the setting package-wait-minutes in a run's words.
const packageWaitSetting = "package-wait-minutes"
// runSettingsOf reads the settings composition-runs-cap-mib, composition-runs-kept, composition-step-bound, // runSettingsOf reads the settings composition-runs-cap-mib, composition-runs-kept, composition-step-bound,
// run-untaken-bound and blame-tries from the files the environment names (A-469x, as outsideSettings): a missing or empty // run-untaken-bound, blame-tries and package-wait-minutes from the files the environment names (A-469x, as outsideSettings): a
// file is its default; a content that is no positive whole number or Go duration is an error naming the file. // missing or empty file is its default; a content that is no positive whole number or Go duration is an error naming the file.
func runSettingsOf(getenv func(string) string) (runSettings, error) { func runSettingsOf(getenv func(string) string) (runSettings, error) {
s := defaultRunSettings s := defaultRunSettings
s.packageWait = 10 * packageWaitUnit
minutes, err := settingFile(getenv("MESH_ASSIGNER_PACKAGE_WAIT_FILE"))
if err != nil {
return s, err
}
if minutes > 0 {
s.packageWait = time.Duration(minutes) * packageWaitUnit
}
mib, err := settingFile(getenv("MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE")) mib, err := settingFile(getenv("MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE"))
if err != nil { if err != nil {
return s, err return s, err
@@ -255,6 +275,10 @@ type compositionRuns struct {
mu sync.Mutex mu sync.Mutex
// changed is closed and replaced at each change of the state heard (heard): a step waiting on a run reads its key again. // changed is closed and replaced at each change of the state heard (heard): a step waiting on a run reads its key again.
changed chan struct{} changed chan struct{}
// published holds, by the artifact of a package's publisher (<module>:<artifact>), what is closed and deleted at the seat
// mesh-builds' package-published of that artifact heard (heardPublished), and at each bind of the consumer: a run waiting for
// the package that artifact publishes asks published again (design 47 H2 H-A-628 (3), H-A-630 (1); H-A-326).
published map[string]chan struct{}
// seen are the keys the state's watch handed and has not seen deleted: a listing of the bucket misses a key that is // seen are the keys the state's watch handed and has not seen deleted: a listing of the bucket misses a key that is
// being written at that moment, so every lookup takes these beside it (keys). // being written at that moment, so every lookup takes these beside it (keys).
seen map[string]bool seen map[string]bool
@@ -268,7 +292,98 @@ type compositionRuns struct {
} }
func newCompositionRuns(kv runsKV, set runSettings, now func() time.Time, logf func(string, ...any)) *compositionRuns { func newCompositionRuns(kv runsKV, set runSettings, now func() time.Time, logf func(string, ...any)) *compositionRuns {
return &compositionRuns{kv: kv, set: set, now: now, logf: logf, changed: make(chan struct{})} return &compositionRuns{kv: kv, set: set, now: now, logf: logf, changed: make(chan struct{}), published: map[string]chan struct{}{}}
}
// heardPublished wakes the runs waiting for the package artifact publishes, at the seat mesh-builds' package-published of that
// artifact heard: each reads published again, the event only its second path; a publish of another package wakes none, so it asks
// no published (design 47 H2 H-A-628 (3), H-A-630 (1); H-A-326, H-A-328).
func (r *compositionRuns) heardPublished(artifact string) {
r.mu.Lock()
defer r.mu.Unlock()
if w, ok := r.published[artifact]; ok {
close(w)
delete(r.published, artifact)
}
}
// heardBind wakes every run waiting for a package's publish, at each bind of the assigner's consumer of package-published, which
// hears no event said before it was made: each reads published again.
func (r *compositionRuns) heardBind() {
r.mu.Lock()
defer r.mu.Unlock()
for artifact, w := range r.published {
close(w)
delete(r.published, artifact)
}
}
// publishWake is closed at the next package-published of artifact heard, or the consumer's next bind.
func (r *compositionRuns) publishWake(artifact string) <-chan struct{} {
r.mu.Lock()
defer r.mu.Unlock()
w, ok := r.published[artifact]
if !ok {
w = make(chan struct{})
r.published[artifact] = w
}
return w
}
// hearPublished hears the seat mesh-builds' package-published on the assigner's durable consumer: the runs waiting for the
// package its artifact publishes are woken (heardPublished, design 47 H2 H-A-630 (1)); one that does not read wakes none and is
// journaled. Each bind of the consumer wakes every waiting run (heardBind, H-A-630 (2)): an event said while it was not bound is
// never heard, so no run waits until its bound alone ends it while its package stands published.
func hearPublished(hub interface {
Handle(string, func(jetstream.Msg)) error
OnBound(func(time.Time))
}, r *compositionRuns, logf func(string, ...any)) error {
hub.OnBound(func(time.Time) { r.heardBind() })
return hub.Handle(meshbuilds.SubjectPackagePublished, func(m jetstream.Msg) {
ev, _, err := meshbuilds.DecodePackagePublishedEvent(m.Data())
if err != nil || ev.Artifact == "" {
logf("%s holds what is no package-published naming its artifact, so it wakes no composition run: %v", m.Subject(), err)
_ = m.Ack()
return
}
r.heardPublished(ev.Artifact)
_ = m.Ack()
})
}
// waitFor writes on the run of ask the package it waits for, `waits` (design 47 H2 H-A-629 (1)), with the words of the entry
// that names it with no version (H-A-631), by compare-and-set: the time its wait began is kept where the run holds one already (a
// start taken up again, H-A-629 (3)), else it is now. It answers that time, and false when the key holds another run, or the run
// ended or has its program.
func (r *compositionRuns) waitFor(key, ask, path, entry string) (time.Time, bool, error) {
var since time.Time
held := false
_, _, err := r.change(key, func(c *meshwants.CompositionRun) bool {
if held = c.Ask == ask && c.Ended == nil && c.Program == nil; !held {
return false
}
since = r.now().UTC()
if c.Waits != nil {
since = c.Waits.Since
if c.Waits.Package == path && c.Waits.Entry == entry {
return false
}
}
c.Waits = &meshwants.CompositionRunWaits{Package: path, Entry: entry, Since: since}
return true
})
return since, held, err
}
// pastWaitSaid is the end of a run of machine whose wait for the publish of the package path, which the entry names with no
// version, passed package-wait-minutes: it names the package, the entry and the bound on every path that ends it, the waiting
// start's, the bound's expiry and the take-up's, each from `waits` (design 47 H2 H-A-628 (3), (5); H-A-630 (4); H-A-631).
func (r *compositionRuns) pastWaitSaid(machine string, w meshwants.CompositionRunWaits) string {
said := fmt.Sprintf("package %s has no published version within %s (%s), named with no version in %s", w.Package, r.set.packageWait, packageWaitSetting, w.Entry)
if machine != "" {
said = machine + ": " + said
}
return said
} }
// heard takes a change of the state from its watch (a module watches its own state, principle 1). // heard takes a change of the state from its watch (a module watches its own state, principle 1).
@@ -642,6 +757,7 @@ func (r *compositionRuns) end(key, ask, outcome, said string, verdict map[string
} }
at := r.now().UTC() at := r.now().UTC()
c.Ended, c.Outcome, c.Said, c.Verdict = &at, outcome, said, verdict c.Ended, c.Outcome, c.Said, c.Verdict = &at, outcome, said, verdict
c.Waits = nil // a run's wait ends with it (H-A-629 (1))
ended = true ended = true
return true return true
}) })
@@ -702,6 +818,11 @@ func (r *compositionRuns) heardEnd(e buildstep.StepEnded, read func(buildstep.St
// await waits until each run of keys has ended, through the state's changes heard, or ctx ends: it answers each run as it // await waits until each run of keys has ended, through the state's changes heard, or ctx ends: it answers each run as it
// stands then; a key gone could not run. // stands then; a key gone could not run.
func (r *compositionRuns) await(ctx context.Context, keys []string) map[string]meshwants.CompositionRun { func (r *compositionRuns) await(ctx context.Context, keys []string) map[string]meshwants.CompositionRun {
return r.awaitEach(ctx, keys, nil)
}
// awaitEach is await, handing each read of the runs, as they stand, to each before it waits again; nil hands none.
func (r *compositionRuns) awaitEach(ctx context.Context, keys []string, each func(map[string]meshwants.CompositionRun)) map[string]meshwants.CompositionRun {
out := map[string]meshwants.CompositionRun{} out := map[string]meshwants.CompositionRun{}
for { for {
wake := r.wake() wake := r.wake()
@@ -722,6 +843,9 @@ func (r *compositionRuns) await(ctx context.Context, keys []string) map[string]m
} }
out[key] = run out[key] = run
} }
if each != nil {
each(out)
}
if !open { if !open {
return out return out
} }
@@ -324,7 +324,8 @@ func TestACompositionRunIsOneKeyPerCandidateAndMachine(t *testing.T) {
t.Run("settings", func(t *testing.T) { t.Run("settings", func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
files := map[string]string{"MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE": "8", "MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "2h", files := map[string]string{"MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE": "8", "MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "2h",
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "2s", "MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "", "MESH_ASSIGNER_BLAME_TRIES_FILE": "5"} "MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "2s", "MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "", "MESH_ASSIGNER_BLAME_TRIES_FILE": "5",
"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "3"} // package-wait-minutes in minutes (design 47 H2 H-A-628 (3))
env := map[string]string{} env := map[string]string{}
for name, content := range files { for name, content := range files {
p := filepath.Join(dir, name) p := filepath.Join(dir, name)
@@ -334,7 +335,8 @@ func TestACompositionRunIsOneKeyPerCandidateAndMachine(t *testing.T) {
env[name] = p env[name] = p
} }
s, err := runSettingsOf(func(k string) string { return env[k] }) s, err := runSettingsOf(func(k string) string { return env[k] })
if err != nil || s.capBytes != 8<<20 || s.kept != 2*time.Hour || s.stepBound != 2*time.Second || s.untaken != 24*time.Hour || s.blameTries != 5 { if err != nil || s.capBytes != 8<<20 || s.kept != 2*time.Hour || s.stepBound != 2*time.Second || s.untaken != 24*time.Hour || s.blameTries != 5 ||
s.packageWait != 3*time.Minute {
t.Errorf("settings %+v %v", s, err) t.Errorf("settings %+v %v", s, err)
} }
_ = os.WriteFile(env["MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE"], []byte("30"), 0o600) _ = os.WriteFile(env["MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE"], []byte("30"), 0o600)
@@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings" "strings"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -16,6 +17,7 @@ import (
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient/enginereads" "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient/enginereads"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs"
meshbuilds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
@@ -31,8 +33,25 @@ import (
// machine on the Go build seat's check queue under its name, its program the node-engine build each machine runs; the stand-in // machine on the Go build seat's check queue under its name, its program the node-engine build each machine runs; the stand-in
// build seat reads each request by the seat mesh-wants' verb input in chunks and says its step-ended with the composer's verdict; // build seat reads each request by the seat mesh-wants' verb input in chunks and says its step-ended with the composer's verdict;
// the step's step-ended fails naming the machine that does not compose, warns of the machine away, and no input stays kept. // the step's step-ended fails naming the machine that does not compose, warns of the machine away, and no input stays kept.
// 1984/AC11 (design 47 H2 H-A-628 (2) to (5), H-A-629): the node-engine's entry names the package x/go with no version, and x's
// build in the step's revision publishes it: each run waits while the seat mesh-builds' published answers not published, and
// puts its run ask with x/go at the version published once the package-published is heard; a restart during the wait takes the
// runs up, the one past package-wait-minutes ending could not run naming the package, the other's start run again composing
// after a publish heard while the assigner was down; a run whose wait passes its bound ends could not run naming the package
// and the bound, never "no pin … the builder pins or waits", with no run ask put.
func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T) { func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T) {
b := startBed(t, "") b := startBed(t, "")
t.Cleanup(func() {
if t.Failed() {
b.journal.mu.Lock()
t.Log(b.journal.text.String())
b.journal.mu.Unlock()
}
})
packageWaitUnit = time.Second // package-wait-minutes in seconds at the test's unit
t.Cleanup(func() { packageWaitUnit = time.Minute })
b.settings = map[string]string{"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "30"}
const pkg = "git.novox.be/novox/x/go"
nc, err := nats.Connect(b.srv.ClientURL()) nc, err := nats.Connect(b.srv.ClientURL())
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -43,7 +62,7 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
// machine-back, as the grants part derives them from its consumes; what each node runs it hears on its kept stream (the bed's). // machine-back, as the grants part derives them from its consumes; what each node runs it hears on its kept stream (the bed's).
if _, err := b.js.CreateOrUpdateConsumer(b.ctx, "EVENTS", jetstream.ConsumerConfig{Durable: "n1_mesh-delivery-assigner", if _, err := b.js.CreateOrUpdateConsumer(b.ctx, "EVENTS", jetstream.ConsumerConfig{Durable: "n1_mesh-delivery-assigner",
FilterSubjects: []string{enginereads.SubjectPrefix + "*", "mesh.mod." + buckets.IndexerModule + ".event.views.>", meshcatalog.SubjectCatalogRevisionAll, FilterSubjects: []string{enginereads.SubjectPrefix + "*", "mesh.mod." + buckets.IndexerModule + ".event.views.>", meshcatalog.SubjectCatalogRevisionAll,
nodebuildgo.SubjectStepEndedAll, meshwatchdogs.SubjectMachineAwayAll, meshwatchdogs.SubjectMachineBackAll}, AckPolicy: jetstream.AckExplicitPolicy}); err != nil { nodebuildgo.SubjectStepEndedAll, meshwatchdogs.SubjectMachineAwayAll, meshwatchdogs.SubjectMachineBackAll, meshbuilds.SubjectPackagePublished}, AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for _, node := range []string{"n1", "n2"} { for _, node := range []string{"n1", "n2"} {
@@ -59,10 +78,12 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
} }
// The trunk's catalog half holds the module and the node-engine, the module claiming the seat node-engine. // The trunk's catalog half holds the module and the node-engine, the module claiming the seat node-engine.
engine := meshcatalog.CatalogEntry{Module: "engine", Fp: "src2:e1", Repository: "novox/mesh-host", Commit: engineCommit, Path: ".", engine := meshcatalog.CatalogEntry{Module: "engine", Fp: "src2:e1", Repository: "novox/mesh-host", Commit: engineCommit, Path: ".",
Serves: []string{nodeengine.Seat + ".composition"}, Manifest: map[string]any{"module": "engine", "version": "0.1"}} Serves: []string{nodeengine.Seat + ".composition"}, Manifest: map[string]any{"module": "engine", "version": "0.1"}, Packages: map[string]string{pkg: ""}}
b.cat.mu.Lock() b.cat.mu.Lock()
b.cat.entries[trunkBranch] = map[string]meshcatalog.CatalogEntry{"engine": engine, b.cat.entries[trunkBranch] = map[string]meshcatalog.CatalogEntry{"engine": engine,
"m": {Module: "m", Fp: "src2:m1", Repository: "novox/m", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "m", "version": "0.1"}}} "m": {Module: "m", Fp: "src2:m1", Repository: "novox/m", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "m", "version": "0.1"}},
"x": {Module: "x", Fp: "src2:x1", Repository: "novox/x", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "x", "version": "0.1"},
Artifacts: []meshcatalog.Artifact{{Ref: "x:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: pkg}}}}}
b.cat.rev[trunkBranch] = 3 b.cat.rev[trunkBranch] = 3
b.cat.mu.Unlock() b.cat.mu.Unlock()
for _, node := range []string{"n1", "n2", "n3"} { for _, node := range []string{"n1", "n2", "n3"} {
@@ -72,7 +93,10 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
asked := make(chan string, 8) asked := make(chan string, 8)
engines, err := nc.Subscribe("mesh.seat.node-engine.call.compose-candidate.*.*", func(m *nats.Msg) { engines, err := nc.Subscribe("mesh.seat.node-engine.call.compose-candidate.*.*", func(m *nats.Msg) {
node := strings.Split(m.Subject, ".")[5] node := strings.Split(m.Subject, ".")[5]
asked <- node select { // the first step's asks are read; a later step's runs ask again
case asked <- node:
default:
}
raw, _ := json.Marshal(map[string]any{"result": map[string]any{"candidate": "main.3", "node": node, "verdict": "composed", "input": map[string]any{"node": node}, raw, _ := json.Marshal(map[string]any{"result": map[string]any{"candidate": "main.3", "node": node, "verdict": "composed", "input": map[string]any{"node": node},
"modules": []any{}, "own": map[string]any{}, "took": 1, "v": 1}, "node": node}) "modules": []any{}, "own": map[string]any{}, "took": 1, "v": 1}, "node": node})
_ = m.Respond(raw) _ = m.Respond(raw)
@@ -90,9 +114,23 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { _ = entries.Unsubscribe() }) t.Cleanup(func() { _ = entries.Unsubscribe() })
// The seat mesh-builds' published answers x's build published at 0.1.9 once pub is set (H-A-328).
var pub atomic.Bool
publishedAsks, err := nc.Subscribe("mesh.seat.mesh-builds.call.published.*", func(m *nats.Msg) {
a := meshbuilds.PublishedAnswer{}
if pub.Load() {
a = meshbuilds.PublishedAnswer{Published: true, Version: "0.1.9"}
}
raw, _ := json.Marshal(map[string]any{"result": a, "node": "n0"})
_ = m.Respond(raw)
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = publishedAsks.Unsubscribe() })
subscribed(t, nc) subscribed(t, nc)
// The runner hears the step's end. // The runner hears the step's end.
ended := make(chan meshwants.StepEnded, 1) ended := make(chan meshwants.StepEnded, 8)
ends, err := nc.Subscribe("mesh.seat.mesh-wants.event.step-ended.n1", func(m *nats.Msg) { ends, err := nc.Subscribe("mesh.seat.mesh-wants.event.step-ended.n1", func(m *nats.Msg) {
var e meshwants.StepEnded var e meshwants.StepEnded
_ = json.Unmarshal(m.Data, &e) _ = json.Unmarshal(m.Data, &e)
@@ -105,7 +143,7 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
subscribed(t, nc) subscribed(t, nc)
from := b.journal.mark() from := b.journal.mark()
b.start(t) _, stop := b.startStoppable(t)
b.journal.await(t, from, "the composition step is pulled from", "the composition step served", 30*time.Second) b.journal.await(t, from, "the composition step is pulled from", "the composition step served", 30*time.Second)
b.journal.await(t, from, "n3 is away (machine-away)", "the machine-away of n3 heard", 30*time.Second) b.journal.await(t, from, "n3 is away (machine-away)", "the machine-away of n3 heard", 30*time.Second)
@@ -116,6 +154,16 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
} }
putStep(b.ctx, t, b.js, "step-ask-1", meshwants.StepRun{Pipeline: "main.3.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch, putStep(b.ctx, t, b.js, "step-ask-1", meshwants.StepRun{Pipeline: "main.3.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
Revision: 3, Commit: engineCommit, Fingerprint: "src2:m1"}) Revision: 3, Commit: engineCommit, Fingerprint: "src2:m1"})
// Each machine's run waits for x/go's publish, the step saying fetch; the publish heard, each puts its run ask (1984/AC11).
for _, node := range []string{"n1", "n2"} {
b.journal.await(t, from, "the composition run main=2e3."+node+" waits for package "+pkg, "the run of "+node+" waits", 30*time.Second)
}
b.journal.await(t, from, "the composition step of m says fetch", "the step says fetch", 30*time.Second)
pub.Store(true)
published, _ := json.Marshal(meshbuilds.PackagePublished{V: 1, Module: "x", Artifact: "x:go", Version: "0.1.9", Digest: "sha256:x", Branch: trunkBranch, Source: 3})
if _, err := b.js.Publish(b.ctx, meshbuilds.SubjectPackagePublished, published); err != nil {
t.Fatal(err)
}
// The stand-in Go build seat takes the run asks put under the assigner's name, reads each request by the verb input and says // The stand-in Go build seat takes the run asks put under the assigner's name, reads each request by the verb input and says
// its end with the composer's verdict: n1 composes, n2 does not. // its end with the composer's verdict: n1 composes, n2 does not.
@@ -146,6 +194,9 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
} }
node := req.Machines[0] node := req.Machines[0]
programs[node] = a.Run.Program.Commit programs[node] = a.Run.Program.Commit
if a.Packages[pkg] != "v0.1.9" {
t.Errorf("the composer of %s is built against %v, want x/go at v0.1.9 from published", node, a.Packages)
}
m := composer.Machine{Composes: true} m := composer.Machine{Composes: true}
if node == "n2" { if node == "n2" {
m = composer.Machine{Reason: "two modules own one path", Problems: []string{"/etc/x"}} m = composer.Machine{Reason: "two modules own one path", Problems: []string{"/etc/x"}}
@@ -170,10 +221,14 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
if programs["n1"] != engineCommit || programs["n2"] != engineCommit { if programs["n1"] != engineCommit || programs["n2"] != engineCommit {
t.Errorf("the composers were built at %v, want the node-engine build each machine runs", programs) t.Errorf("the composers were built at %v, want the node-engine build each machine runs", programs)
} }
close(asked) for drained := false; !drained; {
for node := range asked { select {
if node == "n3" { case node := <-asked:
t.Error("the machine away was asked for its input") if node == "n3" {
t.Error("the machine away was asked for its input")
}
default:
drained = true
} }
} }
// The run's end comes before the input's delete (A-470o, A-470p): the inputs go after the step's end, heard by their watch. // The run's end comes before the input's delete (A-470o, A-470p): the inputs go after the step's end, heard by their watch.
@@ -196,6 +251,101 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
} }
} }
queueEmpty(b.ctx, t, b.js) // the step's ask acknowledged at its end (design 47 H2 §777) queueEmpty(b.ctx, t, b.js) // the step's ask acknowledged at its end (design 47 H2 §777)
// A restart during the wait (H-A-629 (3)): the runs of the next revision wait, the assigner stops, n2's wait is aged past
// package-wait-minutes as if the assigner were down that long, and x/go is published with no event heard. The start takes
// both up: n2's ends could not run naming the package; n1's start runs again, reads published first and composes.
revision := func(n int64) {
b.cat.mu.Lock()
b.cat.rev[trunkBranch] = n
b.cat.mu.Unlock()
}
stepEnd := func(id string) meshwants.StepEnded {
t.Helper()
for {
select {
case e := <-ended:
if e.ID == id {
return e
}
case <-time.After(30 * time.Second):
t.Fatalf("the step %s said no end within 30 s", id)
}
}
}
pub.Store(false)
revision(4)
from = b.journal.mark()
putStep(b.ctx, t, b.js, "step-ask-2", meshwants.StepRun{Pipeline: "main.4.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
Revision: 4, Commit: engineCommit, Fingerprint: "src2:m1"})
for _, node := range []string{"n1", "n2"} {
b.journal.await(t, from, "the composition run main=2e4."+node+" waits for package "+pkg, "the run of "+node+" waits", 30*time.Second)
}
stop()
runs := b.buckets[buckets.CompositionRuns()]
e2, err := runs.Get(b.ctx, "main=2e4.n2")
if err != nil {
t.Fatal(err)
}
var waiting meshwants.CompositionRun
if err := json.Unmarshal(e2.Value(), &waiting); err != nil || waiting.Waits == nil || waiting.Waits.Package != pkg ||
waiting.Waits.Entry != "the node-engine's entry src2:e1" || waiting.Program != nil {
t.Fatalf("the waiting run of n2 holds %s (%v), want waits naming x/go and its entry, and no program", e2.Value(), err)
}
waiting.Waits.Since = waiting.Waits.Since.Add(-time.Hour)
aged, _ := json.Marshal(waiting)
if _, err := runs.Update(b.ctx, "main=2e4.n2", aged, e2.Revision()); err != nil {
t.Fatal(err)
}
pub.Store(true)
from = b.journal.mark()
_, stop = b.startStoppable(t)
b.journal.await(t, from, "the composition run main=2e4.n1, waiting for package "+pkg, "the run of n1 taken up", 30*time.Second)
got, err := worker.Next(jetstream.FetchMaxWait(30 * time.Second))
if err != nil {
t.Fatalf("no run ask is put after the restart: %v", err)
}
_ = got.Ack()
a, err := buildstep.DecodeStepAsk(got.Data())
if err != nil || a.Run == nil || a.Packages[pkg] != "v0.1.9" {
t.Fatalf("the run ask after the restart %+v (%v), want x/go at v0.1.9", a, err)
}
if req, err := composer.Decode(readInput(t, nc, a.Run.Input)); err != nil || len(req.Machines) != 1 || req.Machines[0] != "n1" {
t.Fatalf("the run ask after the restart composes %+v (%v), want n1", req.Machines, err)
}
v, _ := json.Marshal(composer.Verdict{V: composer.Version, Cases: []composer.CaseVerdict{{Name: changeCase, Machines: map[string]composer.Machine{"n1": {Composes: true}}}}})
end, _ := json.Marshal(buildstep.StepEnded{V: 1, ID: a.ID, Ask: a.ID, Asker: runAsker, Node: "b1", Outcome: buildstep.OutcomePassed, Output: string(v), At: time.Now().UTC()})
if _, err := b.js.Publish(b.ctx, nodebuildgo.SubjectStepEnded("b1"), end); err != nil {
t.Fatal(err)
}
if e := stepEnd("step-ask-2"); e.Outcome != meshwants.StepEndedOutcomeCouldNotRun || strings.Contains(e.Said, "the builder pins or waits") ||
!strings.Contains(e.Said, "n2: package "+pkg+" has no published version within 30s (package-wait-minutes), named with no version in the node-engine's entry src2:e1") ||
strings.Contains(e.Said, "n1") {
t.Fatalf("the step taken up ended %+v, want could not run naming n2's package past its bound alone", e)
}
// Past the bound while running (H-A-628 (3), (4)): with package-wait-minutes at one, nothing is published, the bound's expiry
// ends each run could not run naming the package, the entry and the bound (H-A-630 (4), H-A-631), and no run ask is put.
stop()
b.settings["MESH_ASSIGNER_PACKAGE_WAIT_FILE"] = "1"
pub.Store(false)
revision(5)
from = b.journal.mark()
_, stop = b.startStoppable(t)
b.journal.await(t, from, "the composition step is pulled from", "the composition step served again", 30*time.Second)
putStep(b.ctx, t, b.js, "step-ask-3", meshwants.StepRun{Pipeline: "main.5.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
Revision: 5, Commit: engineCommit, Fingerprint: "src2:m1"})
e3 := stepEnd("step-ask-3")
for _, node := range []string{"n1", "n2"} {
if want := node + ": package " + pkg + " has no published version within 1s (package-wait-minutes), named with no version in the node-engine's entry src2:e1"; e3.Outcome != meshwants.StepEndedOutcomeCouldNotRun ||
!strings.Contains(e3.Said, want) || strings.Contains(e3.Said, "the builder pins or waits") {
t.Fatalf("the step past its bound ended %+v, want could not run saying %q", e3, want)
}
}
if info, err := worker.Info(b.ctx); err != nil || info.NumPending != 0 || info.NumAckPending != 0 {
t.Errorf("run asks were put past the bound: %+v %v", info, err)
}
stop()
} }
// readInput reads a run's input as a build seat does: the seat mesh-wants' verb input answers its digest and chunk count, then its // readInput reads a run's input as a build seat does: the seat mesh-wants' verb input answers its digest and chunk count, then its
@@ -5,6 +5,8 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"os"
"path/filepath"
"slices" "slices"
"strings" "strings"
"sync" "sync"
@@ -19,6 +21,7 @@ import (
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/testbus"
"mesh-delivery-assigner/internal/assign" "mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assigngraph" "mesh-delivery-assigner/internal/assigngraph"
@@ -95,33 +98,62 @@ func TestTheWantsAreSaidWantedFromTheKeptAssignmentGraphRevision(t *testing.T) {
if err := json.Unmarshal(events[len(events)-1].body, &w); err != nil || len(events) != 3 || !w.Removed || w.Fp != fpTest { if err := json.Unmarshal(events[len(events)-1].body, &w); err != nil || len(events) != 3 || !w.Removed || w.Fp != fpTest {
t.Errorf("a removing want said %+v (%v), %d events", w, err, len(events)) t.Errorf("a removing want said %+v (%v), %d events", w, err, len(events))
} }
// Design 47 H2 §813 (1), H-A-416: a want carries its run, its pipeline's source in decimal, or the newest source held for a // Design 47 H2 §813 (1), H-A-504 corrected, its addendum and its third addendum: a want of a pipeline carries its run, the
// want of no pipeline; it is written by compare-and-set refusing a lower run, and one that differs only by its run stands. // pipeline's sequence the want rule set, as information; a want of no pipeline the newest source held. The order is the bus's:
// a want is written by compare-and-set on the key's revision the pass read, whatever its run, and one that differs only by its
// run stands; a pass whose read the key has moved past writes nothing, says so once, and the next pass writes it.
t.Run("a want's run", func(t *testing.T) { t.Run("a want's run", func(t *testing.T) {
wkey, _ := mwc.WantKey("g14", "db") wkey, _ := mwc.WantKey("g14", "db")
stored := func() mwc.Want { w, _ := mwc.DecodeWant(kv.values[wkey]); return w } stored := func() mwc.Want { w, _ := mwc.DecodeWant(kv.values[wkey]); return w }
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1}) p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1, Run: "212"})
if w := stored(); w.Run != "12" || w.Pipeline != "main.12" { if w := stored(); w.Run != "212" || w.Pipeline != "main.12" {
t.Fatalf("the want of pipeline main.12 is %+v, want run 12", w) t.Fatalf("the want of pipeline main.12 is %+v, want run 212", w)
}
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1, Run: "211"})
if w := stored(); w.Run != "211" || w.Version != "0.1.1" {
t.Errorf("a want of a lower run left %+v, want it written: the run is no gate", w)
} }
puts := kv.puts puts := kv.puts
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1}) p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1, Run: "211"})
if w := stored(); w.Run != "12" || w.Version != "0.1.2" || kv.puts != puts {
t.Errorf("a want of a lower run replaced %+v (%d writes)", w, kv.puts-puts)
}
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1})
if kv.puts != puts { if kv.puts != puts {
t.Error("a want that stands was written again") t.Error("a want that stands was written again")
} }
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1, Run: "212"})
skey, _ := mwc.WantKey("shanks", "db") skey, _ := mwc.WantKey("shanks", "db")
p.putWant(ctx, "shanks", "db", mwc.Want{Fp: fpTest, Put: true, Words: "put: by hand"}) p.putWant(ctx, "shanks", "db", mwc.Want{Fp: fpTest, Put: true, Words: "put: by hand"})
if w, _ := mwc.DecodeWant(kv.values[skey]); w.Run != "9" { if w, _ := mwc.DecodeWant(kv.values[skey]); w.Run != "9" {
t.Errorf("a put's want is %+v, want the newest source held, 9", w) t.Errorf("a put's want is %+v, want the newest source held, 9", w)
} }
// a placement's build after the delivery of run 12: the newest source held for it is the want's own, never refused // a placement's build after the delivery of run 212: the newest source held for it is the want's own
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.0"}) p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.0"})
if w := stored(); w.Run != "12" || w.Version != "0.1.0" { if w := stored(); w.Run != "212" || w.Version != "0.1.0" {
t.Errorf("a placement's want after run 12 is %+v, want it written at run 12", w) t.Errorf("a placement's want after run 212 is %+v, want it written at run 212", w)
}
// Wants written before the sequence carry a revision number (322) as their run: a want of a lower sequence is written.
nkey, _ := mwc.WantKey("novox", "node-tools")
atNovox := func() mwc.Want { w, _ := mwc.DecodeWant(kv.values[nkey]); return w }
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.96", Pipeline: "main.265.again.2", Rank: 1, Run: "322"})
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.115", Pipeline: "main.320.again.1", Rank: 1, Run: "312"})
if w := atNovox(); w.Run != "312" || w.Version != "0.1.115" {
t.Errorf("seq 312 after run 322 left %+v, want 0.1.115 at run 312", w)
}
// A stale pass: another write moved the key past the revision this pass read; it loses, says so once, writes nothing.
var lines []string
p.logf = func(f string, a ...any) { lines = append(lines, fmt.Sprintf(f, a...)) }
defer func() { p.logf = t.Logf }()
newer, _ := mwc.EncodeWant(mwc.Want{Fp: fpTest, Version: "0.1.116", Pipeline: "main.321", Rank: 1, Run: "313"})
if _, err := kv.Update(ctx, nkey, newer, kv.revision(nkey)); err != nil {
t.Fatal(err)
}
puts = kv.puts
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.114", Pipeline: "main.319", Rank: 1, Run: "311"})
if w := atNovox(); w.Version != "0.1.116" || kv.puts != puts || len(lines) != 1 || !strings.Contains(lines[0], "the newer write stands") {
t.Errorf("a stale pass left %+v (%d writes), said %q", w, kv.puts-puts, lines)
}
p.w.putEntry(buckets.Wants(), nkey, newer, kv.revision(nkey), at) // the watch hands the newer write
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.117", Pipeline: "main.322", Rank: 1, Run: "314"})
if w := atNovox(); w.Version != "0.1.117" || len(lines) != 1 {
t.Errorf("the next pass left %+v, said %q", w, lines)
} }
}) })
@@ -170,15 +202,21 @@ func TestTheWantsAreSaidWantedFromTheKeptAssignmentGraphRevision(t *testing.T) {
} }
// blockedObjects is an object bucket whose listing waits while a gate stands: a keeping that does not end until it is opened. // blockedObjects is an object bucket whose listing waits while a gate stands: a keeping that does not end until it is opened.
// A listing that meets the gate closes entered: the keeping took its need and runs it (H-A-476).
type blockedObjects struct { type blockedObjects struct {
memObjects memObjects
mu sync.Mutex mu sync.Mutex
gate chan struct{} gate chan struct{}
entered chan struct{}
} }
func (b *blockedObjects) Names(ctx context.Context) ([]string, error) { func (b *blockedObjects) Names(ctx context.Context) ([]string, error) {
b.mu.Lock() b.mu.Lock()
gate := b.gate gate, entered := b.gate, b.entered
if gate != nil && entered != nil {
close(entered)
b.entered = nil
}
b.mu.Unlock() b.mu.Unlock()
if gate != nil { if gate != nil {
<-gate <-gate
@@ -204,16 +242,33 @@ func (b *blockedObjects) Get(ctx context.Context, name string) ([]byte, error) {
func (b *blockedObjects) block() func() { func (b *blockedObjects) block() func() {
gate := make(chan struct{}) gate := make(chan struct{})
b.mu.Lock() b.mu.Lock()
b.gate = gate b.gate, b.entered = gate, make(chan struct{})
b.mu.Unlock() b.mu.Unlock()
return func() { return func() {
b.mu.Lock() b.mu.Lock()
b.gate = nil b.gate, b.entered = nil, nil
b.mu.Unlock() b.mu.Unlock()
close(gate) close(gate)
} }
} }
// awaitBlocked returns once a keeping meets the standing gate, so what the keeping took is read after it took it, and fails the
// test when none did within bound (H-A-476: a test waits on the signal of the work it reads after, never on an order it assumes).
func (b *blockedObjects) awaitBlocked(t *testing.T, bound time.Duration, what string) {
t.Helper()
b.mu.Lock()
entered := b.entered
b.mu.Unlock()
if entered == nil {
return // met already
}
select {
case <-entered:
case <-time.After(bound):
t.Fatalf("no keeping met the gate within %s: %s", bound, what)
}
}
// Design 47 H-A-259, H-A-261: the keeping of the assignment graph runs off the pass loop. At the start, while the first keeping is // Design 47 H-A-259, H-A-261: the keeping of the assignment graph runs off the pass loop. At the start, while the first keeping is
// blocked, a pass returns and writes no want; the keeping's end wakes a pass, which writes the passed pipeline's want. Later, while a // blocked, a pass returns and writes no want; the keeping's end wakes a pass, which writes the passed pipeline's want. Later, while a
// keeping of new inputs is blocked, a pass writes the wants from the revision it holds, and a pass of the same inputs hands nothing // keeping of new inputs is blocked, a pass writes the wants from the revision it holds, and a pass of the same inputs hands nothing
@@ -222,6 +277,7 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
fp := mcc.SourcePrefix2 + strings.Repeat("a", 64) fp := mcc.SourcePrefix2 + strings.Repeat("a", 64)
wantsKV := &memKV{values: map[string][]byte{}} wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now()) p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
bound := testbus.SetupBound(t) // every wait on a goroutine's work, never a value in the test (H-A-476)
var mu sync.Mutex var mu sync.Mutex
var journal strings.Builder var journal strings.Builder
p.logf = func(f string, a ...any) { mu.Lock(); fmt.Fprintf(&journal, f+"\n", a...); mu.Unlock() } p.logf = func(f string, a ...any) { mu.Lock(); fmt.Fprintf(&journal, f+"\n", a...); mu.Unlock() }
@@ -252,7 +308,7 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
go func() { p.pass(context.Background()); close(done) }() go func() { p.pass(context.Background()); close(done) }()
select { select {
case <-done: case <-done:
case <-time.After(10 * time.Second): case <-time.After(bound):
t.Fatal("the pass waits on the keeping of the assignment graph") t.Fatal("the pass waits on the keeping of the assignment graph")
} }
} }
@@ -281,7 +337,7 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
open() open()
select { select {
case <-woke: case <-woke:
case <-time.After(10 * time.Second): case <-time.After(bound):
t.Fatal("the first keeping's end wakes no pass") t.Fatal("the first keeping's end wakes no pass")
} }
pass() pass()
@@ -292,7 +348,8 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
open = objects.block() // a keeping of new inputs is blocked open = objects.block() // a keeping of new inputs is blocked
placeOn(t, p.w, "g14", "web") placeOn(t, p.w, "g14", "web")
pass() pass()
pass() // the same inputs again pass() // the same inputs again
objects.awaitBlocked(t, bound, "the keeping of new inputs never took its need") // H-A-476: read the need once it was taken
if w, err := wantOf("g14"); err != nil || w.Fp != fp || w.Version != "0.1.2" { if w, err := wantOf("g14"); err != nil || w.Fp != fp || w.Version != "0.1.2" {
t.Errorf("the want of web on g14 = %+v (%v), want the passed version while a keeping is blocked", w, err) t.Errorf("the want of web on g14 = %+v (%v), want the passed version while a keeping is blocked", w, err)
} }
@@ -352,6 +409,109 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
t.Errorf("assigner_keep_now: %v, asked %v", err, asked) t.Errorf("assigner_keep_now: %v, asked %v", err, asked)
} }
}) })
// 1984/AC13 (design 47 H2 H-A-635): a pass still running after pass-stall-seconds says in the journal which phase it is in, and again at each
// further bound until it ends; one that ends within the bound says none, and its end line stays as it was. The bound is the setting
// read from its file (the unit a millisecond), so a row that blocks a phase waits only for its bounds.
t.Run("a pass past pass-stall-seconds says its phase", func(t *testing.T) {
was := passStallUnit
passStallUnit = time.Millisecond
t.Cleanup(func() { passStallUnit = was })
file := filepath.Join(t.TempDir(), "pass-stall-seconds")
if err := os.WriteFile(file, []byte("20"), 0o600); err != nil {
t.Fatal(err)
}
stall, err := passStallSetting(func(string) string { return file })
if none, noneErr := passStallSetting(func(string) string { return "" }); err != nil || stall != 20*time.Millisecond || noneErr != nil || none != 0 ||
(&passer{}).passStallOf() != time.Minute || (&passer{passStall: stall}).passStallOf() != stall {
t.Fatalf("the setting reads %v (%v), none set %v (%v), the default %v; want 20 units, none set the default of a minute", stall, err, none, noneErr, (&passer{}).passStallOf())
}
for _, row := range []struct {
name, phase string
block func(p *passer, gate chan struct{}) // blocks the phase until the gate closes
}{
{"the kept graph", phaseKeptGraph, func(p *passer, gate chan struct{}) {
p.graph = &graphKeeper{objects: &blockedObjects{memObjects: memObjects{}}, background: func(f func()) { f() }, wake: func() {},
halves: func() map[string]mcc.Half { <-gate; return nil }}
}},
{"the node wants", phaseNodeWants, func(p *passer, gate chan struct{}) {
p.kvs[buckets.Wants()] = &gatedKV{memKV: &memKV{values: map[string][]byte{}}, gate: gate}
}},
} {
t.Run(row.name, func(t *testing.T) {
var mu sync.Mutex
var journal []string
stalled := make(chan string, 64)
p := newPasser(kvSet{buckets.Wants(): &memKV{values: map[string][]byte{}}, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
p.passStall = stall
p.logf = func(f string, a ...any) {
line := fmt.Sprintf(f, a...)
mu.Lock()
journal = append(journal, line)
mu.Unlock()
if strings.Contains(line, "the pass started at ") {
stalled <- line
}
}
placeOn(t, p.w, "ace", "web")
gate := make(chan struct{})
row.block(p, gate)
done := make(chan struct{})
go func() { p.pass(context.Background()); close(done) }()
var earlier time.Duration
for range 2 { // the first bound and the next
select {
case line := <-stalled:
_, after, _ := strings.Cut(line, " is in "+row.phase+" for ")
spent, err := time.ParseDuration(after)
if after == "" || err != nil || spent < earlier {
t.Fatalf("the journal says %q, want the pass in %q for a time that grows", line, row.phase)
}
earlier = spent
case <-time.After(bound):
t.Fatalf("a pass blocked in %s says nothing within %v", row.phase, bound)
}
}
select {
case <-done:
t.Fatal("the pass ended while its phase was blocked")
default:
}
close(gate)
select {
case <-done:
case <-time.After(bound):
t.Fatal("the pass does not end when its phase is opened")
}
mu.Lock()
defer mu.Unlock()
if last := journal[len(journal)-1]; !strings.HasPrefix(last, "the pass took ") {
t.Errorf("the journal ends %q, want the end line of the pass as before", last)
}
})
}
// A pass that ends within the bound says none: the bound is armed once, disarmed at the end, and a bound that still fires
// after the end (as a late timer) says nothing.
var armed []func()
var stopped int
var journal []string
p := newPasser(kvSet{buckets.Wants(): &memKV{values: map[string][]byte{}}, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
p.logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
p.stallAfter = func(d time.Duration, f func()) func() {
if d != time.Minute {
t.Errorf("the bound armed is %v, want the default of a minute", d)
}
armed = append(armed, f)
return func() { stopped++ }
}
p.pass(context.Background())
if len(armed) != 1 || stopped != 1 {
t.Fatalf("the bound was armed %d times and disarmed %d times, want once each", len(armed), stopped)
}
armed[0]()
if len(armed) != 1 || len(journal) != 1 || !strings.HasPrefix(journal[0], "the pass took ") {
t.Errorf("a pass that ended within the bound: journal %q, armed %d; want only its end line", journal, len(armed))
}
})
} }
// failingObjects refuses the next fail puts, then is objects. // failingObjects refuses the next fail puts, then is objects.
@@ -367,3 +527,14 @@ func (f *failingObjects) Put(ctx context.Context, name string, data []byte) erro
} }
return f.blockedObjects.Put(ctx, name, data) return f.blockedObjects.Put(ctx, name, data)
} }
// gatedKV is a bucket whose put waits until the gate closes.
type gatedKV struct {
*memKV
gate chan struct{}
}
func (g *gatedKV) Put(ctx context.Context, key string, value []byte) (uint64, error) {
<-g.gate
return g.memKV.Put(ctx, key, value)
}
@@ -599,7 +599,7 @@ func (b *bed) ended(t *testing.T, source int64, outcome string, movers ...moverA
if outcome != mpr.PipelineEndedOutcomePassed { if outcome != mpr.PipelineEndedOutcomePassed {
step.Outcome = mpr.StepResultOutcomeFailed step.Outcome = mpr.StepResultOutcomeFailed
} }
e := mpr.PipelineEnded{V: 1, Pipeline: pipeline, Branch: trunkBranch, Source: source, Outcome: outcome} e := mpr.PipelineEnded{V: 1, Pipeline: pipeline, Branch: trunkBranch, Source: source, Seq: 200 + source, Outcome: outcome}
for _, m := range movers { for _, m := range movers {
e.Movers = append(e.Movers, mpr.MoverEnded{Module: m.module, Fingerprint: m.fp, Version: m.version, Tier: m.tier, Steps: []mpr.StepResult{step}}) e.Movers = append(e.Movers, mpr.MoverEnded{Module: m.module, Fingerprint: m.fp, Version: m.version, Tier: m.tier, Steps: []mpr.StepResult{step}})
} }
@@ -516,6 +516,12 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
if err := hearRunBounds(hub, runs, logger.Printf); err != nil { if err := hearRunBounds(hub, runs, logger.Printf); err != nil {
logger.Printf("the build seats' ask-taken and step-progress are not heard, so a composition run is ended by no bound: %v", err) logger.Printf("the build seats' ask-taken and step-progress are not heard, so a composition run is ended by no bound: %v", err)
} }
// The seat mesh-builds' package-published wakes the runs waiting for the package its artifact publishes, which read published
// again; each bind of the consumer, which hears no event said before it was made, wakes every waiting run (design 47 H2
// H-A-628 (3), H-A-630 (1), (2); H-A-326, H-A-328).
if err := hearPublished(hub, runs, logger.Printf); err != nil {
logger.Printf("the seat mesh-builds' package-published is not heard, so a composition run waiting for a package reads published only at its start and at each bind: %v", err)
}
} }
if inputs != nil { if inputs != nil {
var runEnded func(buildstep.StepEnded) error var runEnded func(buildstep.StepEnded) error
@@ -593,6 +599,10 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
return err return err
} }
p.tierBound, p.tierWake = tierBound, wake p.tierBound, p.tierWake = tierBound, wake
// The setting pass-stall-seconds: a pass still running after it says which phase it is in (design 47 H2 H-A-635).
if p.passStall, err = passStallSetting(getenv); err != nil {
return err
}
// The wait on an outside cause (outside.go, design 47 G §706): the keeper's three events say when to judge again, and the // The wait on an outside cause (outside.go, design 47 G §706): the keeper's three events say when to judge again, and the
// seat mesh-wants' wait-held and wait-ended are said; registered before the hub starts. // seat mesh-wants' wait-held and wait-ended are said; registered before the hub starts.
if bus != nil && kvs[buckets.Waits()] != nil { if bus != nil && kvs[buckets.Waits()] != nil {
@@ -656,6 +666,7 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
// once the first registrations are written (§95, §353). // once the first registrations are written (§95, §353).
p.ends = newPipelineEnds(kvEnds{ctx, kv}, wake, logger.Printf) p.ends = newPipelineEnds(kvEnds{ctx, kv}, wake, logger.Printf)
p.ends.trunk = w.trunkName p.ends.trunk = w.trunkName
p.ends.releasedOf = w.releasedOf // a version released before its pipeline passed is taken at the pass (H-A-490)
p.ends.runEnded = func(group string) error { return p.dropCandidate(ctx, group) } p.ends.runEnded = func(group string) error { return p.dropCandidate(ctx, group) }
if err := hearEnds(hub, p.ends); err != nil { if err := hearEnds(hub, p.ends); err != nil {
logger.Printf("a pipeline's end is not heard, so the wants keep the trunk-only form until the assigner starts again: %v", err) logger.Printf("a pipeline's end is not heard, so the wants keep the trunk-only form until the assigner starts again: %v", err)
@@ -680,7 +691,7 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
return err return err
} }
run := &compositionRun{runs: runs, inputs: &compositionInputs{machines: w.machinesOf, callFile: bus.CallFileKept, bound: askBound}, keeper: inputs, reads: &compositionReads{}, call: bus.CallKept, callFile: bus.CallFileKept, run := &compositionRun{runs: runs, inputs: &compositionInputs{machines: w.machinesOf, callFile: bus.CallFileKept, bound: askBound}, keeper: inputs, reads: &compositionReads{}, call: bus.CallKept, callFile: bus.CallFileKept,
trunk: trunkOf(iv, w.trunkName), newest: iv.newestOf(), watched: iv.watchedOf, assigned: w.assignedOn, assignment: w.assignmentOf, findings: findings, running: w.runningOf, away: func(machine string) bool { return w.awayNow()[machine] }, put: runAskPublisher(js), ask: bus.CallFile, now: time.Now, logf: logger.Printf} trunk: trunkOf(iv, w.trunkName), newest: iv.newestOf(), watched: iv.watchedOf, assigned: w.assignedOn, assignment: w.assignmentOf, findings: findings, running: w.runningOf, away: func(machine string) bool { return w.awayNow()[machine] }, put: runAskPublisher(js), own: ctx, ask: bus.CallFile, now: time.Now, logf: logger.Printf}
// The seat's work queue (design 47 H2 §777): pulled through its one worker, each ask taken once in the state taken. // The seat's work queue (design 47 H2 §777): pulled through its one worker, each ask taken once in the state taken.
takenBound, err := askTakenBound() takenBound, err := askTakenBound()
if err != nil { if err != nil {
@@ -698,7 +709,8 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
runs.moved.Store(&move) runs.moved.Store(&move)
// The state's watch wakes the steps waiting on a run and hears a bound's expiry; the runs standing at the start are taken up // The state's watch wakes the steps waiting on a run and hears a bound's expiry; the runs standing at the start are taken up
// once the values that stand are read (§719, §720). // once the values that stand are read (§719, §720).
if err := watchRuns(ctx, kvs[buckets.CompositionRuns()], runs, runs.expired, func() { steps.takeUp(ctx, runs) }); err != nil { // A run still waiting for a package's publish has its start run again (H-A-629 (3)).
if err := watchRuns(ctx, kvs[buckets.CompositionRuns()], runs, runs.expired, func() { steps.takeUp(ctx, runs); run.takeUpWaits(ctx) }); err != nil {
return fmt.Errorf("the state %s is not watched: %w", buckets.CompositionRunsState, err) return fmt.Errorf("the state %s is not watched: %w", buckets.CompositionRunsState, err)
} }
// The runs' read and drop, the seat mesh-wants' verbs compositions and compositions-drop (§728, A-469f), answered here // The runs' read and drop, the seat mesh-wants' verbs compositions and compositions-drop (§728, A-469f), answered here
@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"maps"
"mesh-delivery-assigner/internal/buckets" "mesh-delivery-assigner/internal/buckets"
"reflect" "reflect"
"slices" "slices"
@@ -14,6 +15,7 @@ import (
"strings" "strings"
"time" "time"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
@@ -97,6 +99,9 @@ type passer struct {
// saidWaits is the last said of the seat's wait for its states (sayWaits). // saidWaits is the last said of the seat's wait for its states (sayWaits).
saidWaits string saidWaits string
intended map[string]map[string]map[string]bool intended map[string]map[string]map[string]bool
// assignmentLeftSaid is, by assignment key, the why last said that the clean state leaves a retired module's key (H-A-509),
// so each is said once per why.
assignmentLeftSaid map[string]string
// laidHere are the proposals whose candidates this process wrote (design 47 G A-317), by id. // laidHere are the proposals whose candidates this process wrote (design 47 G A-317), by id.
laidHere map[string]bool laidHere map[string]bool
// reads is the assigner's state engine-reads, what each node's engine said it reads (enginewords.go, design 47 H-A-104); // reads is the assigner's state engine-reads, what each node's engine said it reads (enginewords.go, design 47 H-A-104);
@@ -116,6 +121,11 @@ type passer struct {
tierBound time.Duration tierBound time.Duration
tierWake func() tierWake func()
tierTimer *time.Timer tierTimer *time.Timer
// passStall is the setting pass-stall-seconds (passstall.go; zero: its default): a pass still running after it says which phase
// it is in (design 47 H2 H-A-635).
passStall time.Duration
// stallAfter arms a bound of the pass's watch in the place of a timer, returning what disarms it; nil: a timer (a test's seam).
stallAfter func(time.Duration, func()) func()
} }
// wantsSay says one event of the seat mesh-wants; with no bus to say it on, nothing is said. // wantsSay says one event of the seat mesh-wants; with no bus to say it on, nothing is said.
@@ -146,16 +156,28 @@ func (p *passer) clock() time.Time {
func (p *passer) pass(ctx context.Context) { func (p *passer) pass(ctx context.Context) {
start := time.Now() start := time.Now()
defer func() { p.logf("the pass took %s", time.Since(start).Round(time.Millisecond)) }() // design 47 H-A-259 watch := p.watchPass(start) // a pass past pass-stall-seconds says which phase it is in (design 47 H2 H-A-635)
defer func() {
watch.end()
p.logf("the pass took %s", time.Since(start).Round(time.Millisecond)) // design 47 H-A-259
}()
watch.in(phaseAssignmentsSeat)
p.assignmentsSeat(ctx) p.assignmentsSeat(ctx)
watch.in(phaseKeptGraph)
if held := p.keepGraph(ctx); held == "" { if held := p.keepGraph(ctx); held == "" {
watch.in(phaseWants)
p.wants(ctx) p.wants(ctx)
watch.in(phasePassSaid)
p.sayPass(ctx, "judged") p.sayPass(ctx, "judged")
} else { } else {
watch.in(phasePassSaid)
p.sayPass(ctx, held) // a full store keeps the last revision (design 47 G §181); none kept yet writes no want (H-A-261) p.sayPass(ctx, held) // a full store keeps the last revision (design 47 G §181); none kept yet writes no want (H-A-261)
} }
watch.in(phasePuts)
p.puts(ctx) p.puts(ctx)
watch.in(phaseNodeWants)
p.nodeWants(ctx) p.nodeWants(ctx)
watch.in(phaseBackups)
p.backups(ctx, p.reverts(ctx)) p.backups(ctx, p.reverts(ctx))
} }
@@ -222,6 +244,7 @@ func (p *passer) wants(ctx context.Context) {
puts := p.putsByModule() puts := p.putsByModule()
builds := placementBuilds(p.w.assignments()) builds := placementBuilds(p.w.assignments())
p.staleAsks(ctx, trunk) p.staleAsks(ctx, trunk)
p.retiredAssignments(ctx, trunk)
names := map[string]bool{} names := map[string]bool{}
for name := range trunk { for name := range trunk {
names[name] = true names[name] = true
@@ -312,15 +335,14 @@ func (p *passer) putWant(ctx context.Context, node, module string, want mwc.Want
} }
} }
// runOf is the run a want carries (design 47 H2 §813 (1); H-A-355 (1), H-A-416): the source revision of the pipeline that // runOf is the run a want carries (design 47 H2 §813 (1); H-A-355 (1), H-A-504 corrected and its addendum): the sequence of
// released it, `<branch>.<source>`, in decimal; for a want of no pipeline (a put, a placement's build, a removal) the newest // the pipeline that released it, as its pipeline-ended said it, set on the want by the want rule; for a want of no pipeline (a
// source the assigner holds for it: the trunk's source of its kept assignment graph revision, or the run of the want written // put, a placement's build, a removal) the newest source the assigner holds for it: the trunk's source of its kept assignment
// (held) when that is newer, so a person's put or placement after a delivery is never refused as older; "" when it holds none. // graph revision, or the run of the want written (held) when that is newer, so a person's put or placement after a delivery is
// never refused as older; "" when it holds none.
func (p *passer) runOf(want mwc.Want, held *mwc.Want) string { func (p *passer) runOf(want mwc.Want, held *mwc.Want) string {
if i := strings.LastIndexByte(want.Pipeline, '.'); i >= 0 { if want.Run != "" {
if n, err := strconv.ParseInt(want.Pipeline[i+1:], 10, 64); err == nil && n > 0 { return want.Run
return strconv.FormatInt(n, 10)
}
} }
var newest int64 var newest int64
if p.graph != nil { if p.graph != nil {
@@ -343,12 +365,16 @@ func runNumber(run string) int64 {
return n return n
} }
// wantWritten writes the want of module on node under key by compare-and-set, carrying its run (design 47 H2 §813 (1)): a want // wantWritten writes the want of module on node under key, carrying its run as information (design 47 H2 §813 (1), H-A-504
// that differs from the one written only by its run is not written again (its run stays, so a node never composes again for // third addendum): the order is the bus's own, a compare-and-set on the key's revision this pass read, so a stale pass loses to
// it), and one whose run is lower than the run written is refused, said in the journal. It answers whether it wrote. // the newer write, said once in the journal, and the next pass judges the key again from what it then reads. The run is the
// pipeline's sequence for the why and the tools, never a gate. A want that differs from the one written only by its run is
// not written again (its run stays, so a node never composes again for it). It answers whether it wrote.
func (p *passer) wantWritten(ctx context.Context, node, module, key string, want mwc.Want) bool { func (p *passer) wantWritten(ctx context.Context, node, module, key string, want mwc.Want) bool {
raw := p.w.value(buckets.Wants(), key)
read := p.w.metaOf(buckets.Wants(), key).revision
var held *mwc.Want var held *mwc.Want
if raw := p.w.value(buckets.Wants(), key); raw != nil { if raw != nil {
if h, err := mwc.DecodeWant(raw); err == nil { if h, err := mwc.DecodeWant(raw); err == nil {
held = &h held = &h
} }
@@ -359,9 +385,6 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
same.Run = want.Run same.Run = want.Run
if reflect.DeepEqual(same, want) { if reflect.DeepEqual(same, want) {
want.Run = held.Run // it stands: nothing is written want.Run = held.Run // it stands: nothing is written
} else if runNumber(held.Run) > runNumber(want.Run) {
p.logf("the want of %s on %s is not written: its run %q is lower than the run %q written (§813 (1))", module, node, want.Run, held.Run)
return false
} }
} }
value, err := mwc.EncodeWant(want) value, err := mwc.EncodeWant(want)
@@ -369,20 +392,19 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
p.logf("%s %s is not written: %v", buckets.Wants(), key, err) p.logf("%s %s is not written: %v", buckets.Wants(), key, err)
return false return false
} }
if held := p.w.value(buckets.Wants(), key); held != nil && bytes.Equal(held, value) { if raw != nil && bytes.Equal(raw, value) {
return false return false
} }
kv := p.kvs[buckets.Wants()] kv := p.kvs[buckets.Wants()]
entry, err := kv.Get(ctx, key) var revision uint64
switch { if raw == nil {
case errors.Is(err, jetstream.ErrKeyNotFound): revision, err = kv.Create(ctx, key, value)
_, err = kv.Create(ctx, key, value) } else {
case err == nil: revision, err = kv.Update(ctx, key, value, read)
if h, derr := mwc.DecodeWant(entry.Value()); derr == nil && runNumber(h.Run) > runNumber(want.Run) { }
p.logf("the want of %s on %s is not written: its run %q is lower than the run %q written (§813 (1))", module, node, want.Run, h.Run) if errors.Is(err, jetstream.ErrKeyExists) || errors.Is(err, jetstream.ErrKeyRevisionMismatch) || (err != nil && isWrongSequence(err)) {
return false p.logf("the want of %s on %s (run %q) is not written: its key moved past revision %d this pass read, and the newer write stands (§813 (1), H-A-504 third addendum); the next pass judges it again", module, node, want.Run, read)
} return false
_, err = kv.Update(ctx, key, value, entry.Revision())
} }
if err != nil { if err != nil {
if !errors.Is(err, context.Canceled) { if !errors.Is(err, context.Canceled) {
@@ -390,7 +412,7 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
} }
return false return false
} }
p.w.put(buckets.Wants(), key, value) p.w.putEntry(buckets.Wants(), key, value, revision, p.clock())
return true return true
} }
@@ -529,6 +551,42 @@ func (p *passer) staleAsks(ctx context.Context, trunk map[string]meshcatalog.Mod
} }
} }
// retiredAssignments is the clean state of the assignments at the pass (design 47 H2 H-A-509 and its second addendum): each
// module key `<node>.<module>` of a module no manifest the trunk holds names, that the node key does not name, is deleted and
// named in the journal, whether its value reads or not; one the node key still names is left, said once per why. Nothing goes
// while the trunk is empty, or with no assignments bucket open.
func (p *passer) retiredAssignments(ctx context.Context, trunk map[string]meshcatalog.ModulesByModuleValue) {
if len(trunk) == 0 || p.kvs[plc.AssignmentsBucket()] == nil {
return
}
names := make(map[string]bool, len(trunk))
for name := range trunk {
names[name] = true
}
held := p.w.read(plc.AssignmentsBucket())
for _, key := range slices.Sorted(maps.Keys(held)) {
node, module, kind, err := mmac.ParseKey(key)
if err != nil || kind != mmac.ModuleKind || names[module] {
continue
}
nodeKey, _ := mmac.NodeKey(node)
nodeRaw, nodeFound := held[nodeKey]
if left := assignmentLeft(node, module, names, nodeRaw, nodeFound); left != "" {
if p.assignmentLeftSaid[key] != left {
if p.assignmentLeftSaid == nil {
p.assignmentLeftSaid = map[string]string{}
}
p.assignmentLeftSaid[key] = left
p.logf("the assignment key %s is of a module no manifest of the trunk names, and is left: %s", key, left)
}
continue
}
delete(p.assignmentLeftSaid, key)
p.logf("the assignment key %s is of a module no manifest of the trunk names, and is dropped", key)
p.remove(ctx, plc.AssignmentsBucket(), key)
}
}
// remove deletes one key of the assigner's own bucket when it holds it; a delete that fails is said and made again at the next // remove deletes one key of the assigner's own bucket when it holds it; a delete that fails is said and made again at the next
// pass. // pass.
func (p *passer) remove(ctx context.Context, bucket, key string) { func (p *passer) remove(ctx context.Context, bucket, key string) {
@@ -46,19 +46,39 @@ import (
type memKV struct { type memKV struct {
jetstream.KeyValue jetstream.KeyValue
values map[string][]byte values map[string][]byte
puts int // how many puts reached the bucket puts int // how many puts reached the bucket
revs map[string]uint64 // each key's revision, as the bus numbers its writes (a key set by hand has none: its length stands in)
seq uint64
}
// written gives key the bucket's next revision, as a write on the bus does.
func (m *memKV) written(key string) uint64 {
if m.revs == nil {
m.revs = map[string]uint64{}
}
m.seq++
m.revs[key] = m.seq
return m.seq
}
// revision is key's revision as the bucket holds it.
func (m *memKV) revision(key string) uint64 {
if r, ok := m.revs[key]; ok {
return r
}
return uint64(len(m.values[key]))
} }
func (m *memKV) Put(_ context.Context, key string, value []byte) (uint64, error) { func (m *memKV) Put(_ context.Context, key string, value []byte) (uint64, error) {
m.values[key] = value m.values[key] = value
m.puts++ m.puts++
return uint64(len(m.values)), nil return m.written(key), nil
} }
func (m *memKV) Create(_ context.Context, key string, value []byte, _ ...jetstream.KVCreateOpt) (uint64, error) { func (m *memKV) Create(_ context.Context, key string, value []byte, _ ...jetstream.KVCreateOpt) (uint64, error) {
m.values[key] = value m.values[key] = value
m.puts++ // a write that reaches the bucket (the wants' compare-and-set, design 47 H2 §813 (1)) m.puts++ // a write that reaches the bucket (the wants' compare-and-set, design 47 H2 §813 (1))
return uint64(len(m.values)), nil return m.written(key), nil
} }
func (m *memKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error { func (m *memKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
@@ -247,15 +267,15 @@ func (m *memKV) Get(_ context.Context, key string) (jetstream.KeyValueEntry, err
if !ok { if !ok {
return nil, jetstream.ErrKeyNotFound return nil, jetstream.ErrKeyNotFound
} }
return memEntry{value: v, revision: uint64(len(v))}, nil return memEntry{value: v, revision: m.revision(key)}, nil
} }
func (m *memKV) Update(_ context.Context, key string, value []byte, revision uint64) (uint64, error) { func (m *memKV) Update(_ context.Context, key string, value []byte, revision uint64) (uint64, error) {
if uint64(len(m.values[key])) != revision { if m.revision(key) != revision {
return 0, errors.New("wrong last sequence") return 0, fmt.Errorf("wrong last sequence: %w", jetstream.ErrKeyRevisionMismatch)
} }
m.values[key] = value m.values[key] = value
m.puts++ m.puts++
return uint64(len(value)), nil return m.written(key), nil
} }
// memStore is the runtime's states for the put's tools, over the same memKVs a pass writes. // memStore is the runtime's states for the put's tools, over the same memKVs a pass writes.
@@ -266,7 +286,7 @@ func (s memStore) get(state, key string) ([]byte, uint64, bool, error) {
return nil, 0, false, nil return nil, 0, false, nil
} }
v, ok := s[state].values[key] v, ok := s[state].values[key]
return v, uint64(len(v)), ok, nil return v, s[state].revision(key), ok, nil
} }
func (s memStore) put(state, key string, value []byte) error { func (s memStore) put(state, key string, value []byte) error {
s[state].values[key] = value s[state].values[key] = value
@@ -409,7 +429,12 @@ func putOfTheBus(t *testing.T) {
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp, Manifest: mdigest, Repository: "novox/mesh-catalog", Commit: strings.Repeat("c", 40)}) mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp, Manifest: mdigest, Repository: "novox/mesh-catalog", Commit: strings.Repeat("c", 40)})
putModuleRaw(p.w, trunkBranch, "nats", mod) putModuleRaw(p.w, trunkBranch, "nats", mod)
p.w.manifests[mdigest] = parsed{module: "nats", manifest: catalogue.Manifest{Module: "nats", Provides: []catalogue.Offer{{Name: "mesh-bus"}}}} p.w.manifests[mdigest] = parsed{module: "nats", manifest: catalogue.Manifest{Module: "nats", Provides: []catalogue.Offer{{Name: "mesh-bus"}}}}
endDone(t, p.w, "nats", fp, mdigest) // The build and its release (H-A-490 addendum): the put's want names the version released at its parts.
built, _ := json.Marshal(builds.BuildEnded{Module: "nats", Fingerprint: fp, Outcome: builds.BuildDone, Manifest: mdigest, Made: map[string]string{"program": "sha256:5"}})
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "nats", Source: 8, Version: "2.10.1", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "nats:program", Digest: "sha256:5"}}})
if p.w.ends.put(built) != nil || p.w.released.put(rel) != nil {
t.Fatal("the build or its release is not heard")
}
hkey, _ := nodeengineclient.HaveKey("novox", "nats") hkey, _ := nodeengineclient.HaveKey("novox", "nats")
before, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) before, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
world(buckets.Have, hkey, before) world(buckets.Have, hkey, before)
@@ -489,7 +514,7 @@ func putOfTheBus(t *testing.T) {
<-woke <-woke
got = step() got = step()
w, err := mwc.DecodeWant(wantsKV.values["want.novox.nats"]) w, err := mwc.DecodeWant(wantsKV.values["want.novox.nats"])
if got.Step != puts.Wanted || err != nil || w.Fp != fp || !w.Put || !w.Hold { if got.Step != puts.Wanted || err != nil || w.Fp != fp || w.Version != "2.10.1" || !w.Put || !w.Hold {
t.Fatalf("snapshotted, the put stands at %s (%s); the want %+v, %v", got.Step, got.Words, w, err) t.Fatalf("snapshotted, the put stands at %s (%s); the want %+v, %v", got.Step, got.Words, w, err)
} }
if call := <-bus.calls; !strings.HasPrefix(call, "seat:mesh-hand-acts.warranted ") || !strings.Contains(call, a.Ask.ID) { // ADR 0565 §11: into the seat if call := <-bus.calls; !strings.HasPrefix(call, "seat:mesh-hand-acts.warranted ") || !strings.Contains(call, a.Ask.ID) { // ADR 0565 §11: into the seat
@@ -740,12 +765,12 @@ func aPlacedNodesWantsNameTheBuildAloneAndItsYesComesFromItsHave(t *testing.T) {
wkey, _ := mwc.WantKey("g14", "web") wkey, _ := mwc.WantKey("g14", "web")
want, _ := mwc.EncodeWant(mwc.Want{Fp: fpOld, Version: "0.1.1", Pipeline: trunkBranch + ".1", Rank: 1}) want, _ := mwc.EncodeWant(mwc.Want{Fp: fpOld, Version: "0.1.1", Pipeline: trunkBranch + ".1", Rank: 1})
wantsKV.values[wkey] = want wantsKV.values[wkey] = want
put(buckets.Wants(), wkey, want) sync := func() { // as the watch hands the wants, with their revisions
sync := func() {
for k, v := range wantsKV.values { for k, v := range wantsKV.values {
put(buckets.Wants(), k, v) p.w.putEntry(buckets.Wants(), k, v, wantsKV.revision(k), time.Now())
} }
} }
sync()
p.wants(context.Background()) p.wants(context.Background())
p.nodeWants(context.Background()) p.nodeWants(context.Background())
@@ -0,0 +1,98 @@
package main
import (
"sync"
"time"
)
// The phases of a pass, each named as it starts so a pass that stands still can say where (design 47 H2 H-A-635).
const (
phaseAssignmentsSeat = "the assignments seat"
phaseKeptGraph = "the kept graph"
phaseWants = "the wants"
phasePassSaid = "the pass said"
phasePuts = "the puts"
phaseNodeWants = "the node wants"
phaseBackups = "the backups and reverts"
)
// defaultPassStall is the setting pass-stall-seconds' default, 60 seconds (design 47 H2 H-A-635).
const defaultPassStall = 60 * time.Second
// passStallUnit is the unit of the setting pass-stall-seconds, a second; the whole test sets a shorter one, so a pass passes its
// bound without a test waiting seconds (as tierBoundUnit).
var passStallUnit = time.Second
// passStallSetting is the setting pass-stall-seconds, read at the start from the file the manifest declares with the content
// ${config:pass-stall-seconds}; zero, its default, for a file missing or empty (design 47 H2 H-A-635, principle 11).
func passStallSetting(getenv func(string) string) (time.Duration, error) {
seconds, err := settingFile(getenv("MESH_ASSIGNER_PASS_STALL_FILE"))
return time.Duration(seconds) * passStallUnit, err
}
// passStallOf is the setting pass-stall-seconds; zero or less is its default.
func (p *passer) passStallOf() time.Duration {
if p.passStall > 0 {
return p.passStall
}
return defaultPassStall
}
// passWatch is what one running pass keeps of where it stands, in the passer's own memory: its start, the phase it is in and
// since when. A pass still running at the bound says in the journal which phase it is in, and again at each further bound until
// it ends; nothing is said for a pass that ends within the bound, and the end line stays as it was (design 47 H2 H-A-635 on
// H-A-259; principle 3, a part that waits says where; principle 7, a journal line, no new key or event).
type passWatch struct {
logf func(string, ...any)
after func(time.Duration, func()) func()
bound time.Duration
start time.Time
mu sync.Mutex
phase string
since time.Time
stop func()
ended bool
}
// watchPass starts the watch of the pass that began at start; stallAfter, when set, arms the bound in the place of a timer.
func (p *passer) watchPass(start time.Time) *passWatch {
w := &passWatch{logf: p.logf, after: p.stallAfter, bound: p.passStallOf(), start: start, since: start}
if w.after == nil {
w.after = func(d time.Duration, f func()) func() {
t := time.AfterFunc(d, f)
return func() { t.Stop() }
}
}
w.mu.Lock()
defer w.mu.Unlock()
w.stop = w.after(w.bound, w.say)
return w
}
// in says the pass is in phase now.
func (w *passWatch) in(phase string) {
w.mu.Lock()
defer w.mu.Unlock()
w.phase, w.since = phase, time.Now()
}
// say is one bound passed with the pass still running: the journal line, and the next bound armed. The line is said under the
// watch's lock, so none is said after the pass's end has returned.
func (w *passWatch) say() {
w.mu.Lock()
defer w.mu.Unlock()
if w.ended {
return
}
w.stop = w.after(w.bound, w.say)
w.logf("the pass started at %s is in %s for %s", w.start.Format(time.RFC3339), w.phase, time.Since(w.since).Round(time.Millisecond))
}
// end is the pass's end: the bound is disarmed and no further line is said.
func (w *passWatch) end() {
w.mu.Lock()
defer w.mu.Unlock()
w.ended = true
w.stop()
}
@@ -17,6 +17,7 @@ import (
mprc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" mprc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient"
mpcat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" mpcat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/pipelinekey"
stdio "git.novox.be/novox/mesh-sdk/go" stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
@@ -43,8 +44,11 @@ const pipelineEndedSubject = "mesh.seat." + mpr.Seat + ".event." + mpr.EventPipe
type End struct { type End struct {
Pipeline string `json:"pipeline"` Pipeline string `json:"pipeline"`
Source int64 `json:"source"` Source int64 `json:"source"`
Fp string `json:"fp"` // Seq is the pipeline's sequence its pipeline-ended said, written as the run of its wants (design 47 H2 §813 (1), H-A-504
Version string `json:"version"` // addendum).
Seq int64 `json:"seq,omitempty"`
Fp string `json:"fp"`
Version string `json:"version"`
// Rank is the mover's tier in the pipeline's delivery order, from 1 (§746, §750). // Rank is the mover's tier in the pipeline's delivery order, from 1 (§746, §750).
Rank int64 `json:"rank"` Rank int64 `json:"rank"`
} }
@@ -140,6 +144,8 @@ type pipelineEnds struct {
// firsts is, by module, the first watched branch of its registration, the branch of a placement that names none (design // firsts is, by module, the first watched branch of its registration, the branch of a placement that names none (design
// 47 G §14). // 47 G §14).
firsts map[string]string firsts map[string]string
// noSeq is, by module and pipeline, the ends kept without a sequence already said (H-A-504 second addendum).
noSeq map[string]bool
// runEnded is told a run on request's pipeline-ended, its group `run-<id>`, to drop the run's candidate (A-235, H-A-58); nil // runEnded is told a run on request's pipeline-ended, its group `run-<id>`, to drop the run's candidate (A-235, H-A-58); nil
// drops nothing. // drops nothing.
runEnded func(group string) error runEnded func(group string) error
@@ -152,6 +158,10 @@ type pipelineEnds struct {
trunk func() string trunk func() string
// now is the clock of the tier progress (tiers.go); nil is time.Now. // now is the clock of the tier progress (tiers.go); nil is time.Now.
now func() time.Time now func() time.Time
// releasedOf is the version released of module's build at fp, matched by the parts its build.ended made (world.releasedOf):
// a mover whose version was released before its pipeline passed gets its want at the pass (design 47 H2 H-A-490). nil
// matches none.
releasedOf func(module, fp string) (string, bool)
} }
func newPipelineEnds(st endStore, wake func(), logf func(string, ...any)) *pipelineEnds { func newPipelineEnds(st endStore, wake func(), logf func(string, ...any)) *pipelineEnds {
@@ -161,11 +171,25 @@ func newPipelineEnds(st endStore, wake func(), logf func(string, ...any)) *pipel
// take keeps, for each mover of a passed pipeline that released a version, that version as the newest of its module on the // take keeps, for each mover of a passed pipeline that released a version, that version as the newest of its module on the
// pipeline's branch, by compare-and-set on a newer version (design 47 H §750): an older version, or the same one again, writes // pipeline's branch, by compare-and-set on a newer version (design 47 H §750): an older version, or the same one again, writes
// nothing. A passed mover with no version yet is said in the journal and taken when the runner says the end again naming it // nothing. A passed mover with no version yet is said in the journal and taken when the runner says the end again naming it
// (H-A-270); it holds its tier in the pipeline's tier progress meanwhile (H-A-277 (1)). It says whether any key changed. // (H-A-270); it holds its tier in the pipeline's tier progress meanwhile (H-A-277 (1)). A mover whose build's version was
// released before the pass is taken at the pass with that version (H-A-490). It says whether any key changed.
func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) { func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
if p.Outcome != mpr.PipelineEndedOutcomePassed || p.Run != "" { if p.Outcome != mpr.PipelineEndedOutcomePassed || p.Run != "" {
return false, nil return false, nil
} }
// The pipeline's key is read by the one parse of the runner's seat's key forms (design 47 H2 H-A-485): a key it does not
// know is refused loudly, and nothing of the pipeline is kept, never an empty tier progress.
if _, err := pipelinekey.Parse(p.Pipeline); err != nil {
e.logf("the pipeline-ended of %s is refused, and none of its movers' versions is kept: %v", p.Pipeline, err)
return false, nil
}
// Its sequence is its wants' run (design 47 H2 §813 (1), H-A-504 addendum): an end without one, of an older runner, is
// refused loudly and writes no want.
if p.Seq <= 0 {
e.logf("the pipeline-ended of %s is refused, and none of its movers' versions is kept: it carries no seq, the run its "+
"wants would carry (a runner older than H-A-504's addendum); the runner's end-again of %s, once it says seq, keeps them", p.Pipeline, p.Pipeline)
return false, nil
}
changed := false changed := false
var kept []tierMover var kept []tierMover
versioned := map[string]bool{} versioned := map[string]bool{}
@@ -178,6 +202,14 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
if m.Fingerprint == "" || !moverPassed(m) { if m.Fingerprint == "" || !moverPassed(m) {
continue continue
} }
if m.Version == "" && e.releasedOf != nil {
// A version released before its pipeline passed (an again pipeline on a built, published key) is never written
// on the mover, nor its end said again: it is judged at the pass, matched by its build's parts (H-A-490).
if v, ok := e.releasedOf(m.Module, m.Fingerprint); ok {
e.logf("%s: %s passed; its version %s was released before the pass, taken now", p.Pipeline, m.Module, v)
m.Version = v
}
}
if m.Version == "" { if m.Version == "" {
// The runner writes a mover's version at its release's version-released, and says this end again once it does // The runner writes a mover's version at its release's version-released, and says this end again once it does
// (H-A-270 (1), (2)): the skip is said, never silent. // (H-A-270 (1), (2)): the skip is said, never silent.
@@ -199,7 +231,7 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
break // an older version, or this one again break // an older version, or this one again
} }
} }
value, err := json.Marshal(End{Pipeline: p.Pipeline, Source: p.Source, Fp: m.Fingerprint, Version: m.Version, Rank: max(m.Tier, 1)}) value, err := json.Marshal(End{Pipeline: p.Pipeline, Source: p.Source, Seq: p.Seq, Fp: m.Fingerprint, Version: m.Version, Rank: max(m.Tier, 1)})
if err != nil { if err != nil {
return changed, err return changed, err
} }
@@ -216,6 +248,22 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
return changed, nil return changed, nil
} }
// noSeqOnce says, once per module and pipeline, that the end kept for module from pipeline carries no sequence and writes
// no want, naming the recovery (H-A-504 second addendum).
func (e *pipelineEnds) noSeqOnce(module, pipeline string) {
e.mu.Lock()
if e.noSeq == nil {
e.noSeq = map[string]bool{}
}
said := e.noSeq[module+" "+pipeline]
e.noSeq[module+" "+pipeline] = true
e.mu.Unlock()
if !said && e.logf != nil {
e.logf("no want of %s is written: its end kept from %s carries no seq, the run its want would carry (kept before "+
"H-A-504's addendum); the runner's end-again of %s, or %s's next pipeline, writes it", module, pipeline, pipeline, module)
}
}
// endOf is the end kept for module on branch: the newest version released there whose pipeline passed. // endOf is the end kept for module on branch: the newest version released there whose pipeline passed.
func (e *pipelineEnds) endOf(module, branch string) (End, bool) { func (e *pipelineEnds) endOf(module, branch string) (End, bool) {
if e == nil { if e == nil {
@@ -237,7 +285,13 @@ func (e *pipelineEnds) target(module, branch string) (assign.Target, bool) {
if !ok || !e.tierWritten(end) { if !ok || !e.tierWritten(end) {
return assign.Target{}, false return assign.Target{}, false
} }
return assign.Target{Fp: end.Fp, Version: end.Version, Pipeline: end.Pipeline, Rank: end.Rank}, true if end.Seq <= 0 {
// An end kept before pipeline-ended carried its sequence has no run for its wants (design 47 H2 §813 (1), H-A-504
// second addendum): it writes no want, said once.
e.noSeqOnce(module, end.Pipeline)
return assign.Target{}, false
}
return assign.Target{Fp: end.Fp, Version: end.Version, Pipeline: end.Pipeline, Rank: end.Rank, Seq: end.Seq}, true
} }
// hearPipeline takes a pipeline-ended: a passed one's released versions are kept (take), and a run on request's drops the // hearPipeline takes a pipeline-ended: a passed one's released versions are kept (take), and a run on request's drops the
@@ -12,6 +12,7 @@ import (
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient" mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
@@ -67,9 +68,9 @@ func mover(module, fp, version string, tier int64, outcome string) mpr.MoverEnde
Steps: []mpr.StepResult{{Step: "unit", Status: mpr.StepResultStatusRequired, Outcome: outcome, Module: module}}} Steps: []mpr.StepResult{{Step: "unit", Status: mpr.StepResultStatusRequired, Outcome: outcome, Module: module}}}
} }
// ended is the pipeline-ended of the take-in of source on branch, its movers given. // ended is the pipeline-ended of the take-in of source on branch, its movers given, its sequence 200 + source.
func ended(branch string, source int64, outcome string, movers ...mpr.MoverEnded) mpr.PipelineEnded { func ended(branch string, source int64, outcome string, movers ...mpr.MoverEnded) mpr.PipelineEnded {
return mpr.PipelineEnded{V: 1, Branch: branch, Source: source, EndCount: 1, Outcome: outcome, Movers: movers, return mpr.PipelineEnded{V: 1, Branch: branch, Source: source, Seq: 200 + source, EndCount: 1, Outcome: outcome, Movers: movers,
Pipeline: fmt.Sprintf("%s.%d", branch, source)} Pipeline: fmt.Sprintf("%s.%d", branch, source)}
} }
@@ -85,17 +86,34 @@ func TestThePassedVersionIsKept(t *testing.T) {
want *End // nil: none kept for web on main want *End // nil: none kept for web on main
}{ }{
{"a passed pipeline keeps its version", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))}, {"a passed pipeline keeps its version", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))},
&End{Pipeline: "main.5", Source: 5, Fp: "fp1", Version: "0.1.2", Rank: 2}}, &End{Pipeline: "main.5", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 2}},
{"nothing to run counts as passed", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, nothing))}, {"nothing to run counts as passed", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, nothing))},
&End{Pipeline: "main.5", Source: 5, Fp: "fp1", Version: "0.1.2", Rank: 1}}, &End{Pipeline: "main.5", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 1}},
{"a failed pipeline keeps nothing, a passed mover in it neither", []mpr.PipelineEnded{ended("main", 5, fail, mover("web", "fp1", "0.1.2", 1, ok), {"a failed pipeline keeps nothing, a passed mover in it neither", []mpr.PipelineEnded{ended("main", 5, fail, mover("web", "fp1", "0.1.2", 1, ok),
mover("db", "fp9", "0.3.0", 1, failed))}, nil}, mover("db", "fp9", "0.3.0", 1, failed))}, nil},
{"a mover whose required step failed keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, failed))}, nil}, {"a mover whose required step failed keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, failed))}, nil},
{"no version released keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "", 1, ok))}, nil}, {"no version released keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "", 1, ok))}, nil},
{"an older end heard after a newer one keeps the newer", []mpr.PipelineEnded{ended("main", 6, pass, mover("web", "fp2", "0.1.3", 1, ok)), {"an older end heard after a newer one keeps the newer", []mpr.PipelineEnded{ended("main", 6, pass, mover("web", "fp2", "0.1.3", 1, ok)),
ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Fp: "fp2", Version: "0.1.3", Rank: 1}}, ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Seq: 206, Fp: "fp2", Version: "0.1.3", Rank: 1}},
{"a newer version replaces", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok)), {"a newer version replaces", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok)),
ended("main", 6, pass, mover("web", "fp2", "0.1.10", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Fp: "fp2", Version: "0.1.10", Rank: 1}}, ended("main", 6, pass, mover("web", "fp2", "0.1.10", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Seq: 206, Fp: "fp2", Version: "0.1.10", Rank: 1}},
// H-A-485: an again pipeline's end is kept as a take-in's; a key of no form the runner's seat defines is refused, nothing kept.
{"an again pipeline keeps its version", []mpr.PipelineEnded{func() mpr.PipelineEnded {
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))
p.Pipeline = "main.5.again.2"
return p
}()}, &End{Pipeline: "main.5.again.2", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 2}},
{"a key of no form is refused", []mpr.PipelineEnded{func() mpr.PipelineEnded {
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))
p.Pipeline = "main.5.later.2"
return p
}()}, nil},
// H-A-504 addendum: an end without its sequence, of an older runner, is refused and keeps nothing.
{"an end without seq keeps nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded {
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))
p.Seq = 0
return p
}()}, nil},
{"a run on request keeps nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded { {"a run on request keeps nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded {
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok)) p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))
p.Run = "r1" p.Run = "r1"
@@ -109,6 +127,9 @@ func TestThePassedVersionIsKept(t *testing.T) {
} }
} }
got, kept := e.endOf("web", "main") got, kept := e.endOf("web", "main")
if ks, _ := e.st.keys(); c.name == "a key of no form is refused" && len(ks) != 0 {
t.Errorf("%s: the state written holds %v, want nothing (no empty tier progress)", c.name, ks)
}
switch { switch {
case c.want == nil && kept: case c.want == nil && kept:
t.Errorf("%s: kept %+v", c.name, got) t.Errorf("%s: kept %+v", c.name, got)
@@ -142,10 +163,15 @@ func TestThePassedVersionIsKept(t *testing.T) {
// A6/AC1, A5/AC1 (design 47 H §750): a pass writes, on every node the module is assigned to, the want naming the newest version // A6/AC1, A5/AC1 (design 47 H §750): a pass writes, on every node the module is assigned to, the want naming the newest version
// released on its branch whose pipeline passed, with the pipeline and the rank; with none passed it writes none. No grant, // released on its branch whose pipeline passed, with the pipeline and the rank; with none passed it writes none. No grant,
// canary, provider or composition is asked for. H-A-270 (1): a passed end whose mover names no version yet writes no want and // canary, provider or composition is asked for. H-A-270 (1): a passed end whose mover names no version yet writes no want and
// says so in the journal; the same end said again naming the version writes it. // says so in the journal; the same end said again naming the version writes it. H-A-490: a version released before its pipeline
// passed (an again pipeline on a built, published key) gets its want at the pass, matched to the mover's build by its parts.
func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) { func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) {
fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64) fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64)
for _, passed := range []bool{false, true} { for _, c := range []struct {
name string
passed, releasedBefore bool
}{{"no pipeline passed", false, false}, {"passed, then its version released", true, false}, {"released, then its pipeline passed", true, true}} {
passed := c.passed
wantsKV := &memKV{values: map[string][]byte{}} wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now()) p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
p.say = func(oc.Condition) error { return nil } p.say = func(oc.Condition) error { return nil }
@@ -158,7 +184,16 @@ func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) {
var journal []string var journal []string
p.ends = newPipelineEnds(newMemEnds(), func() {}, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }) p.ends = newPipelineEnds(newMemEnds(), func() {}, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
p.ends.trunk = p.w.trunkName p.ends.trunk = p.w.trunkName
if passed { p.ends.releasedOf = p.w.releasedOf
if c.releasedBefore {
// Built and released in an earlier pipeline that failed: the runner's again pipeline ends naming no version.
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "web", Source: 4, Version: "0.1.2", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "web:image", Digest: "sha256:7"}}})
built, _ := json.Marshal(builds.BuildEnded{Module: "web", Fingerprint: fp, Outcome: builds.BuildDone, Made: map[string]string{"image": "sha256:7"}})
if err := p.w.released.put(rel); err != nil || p.w.ends.put(built) != nil {
t.Fatal(err)
}
_, _ = p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("web", fp, "", 2, mpr.StepResultOutcomePassed)))
} else if passed {
_, _ = p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("web", fp, "", 2, mpr.StepResultOutcomePassed))) _, _ = p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("web", fp, "", 2, mpr.StepResultOutcomePassed)))
p.wants(context.Background()) p.wants(context.Background())
if len(wantsKV.values) != 0 || !slices.Contains(journal, trunkBranch+".5: web passed with no version yet: taken again when its version is written") { if len(wantsKV.values) != 0 || !slices.Contains(journal, trunkBranch+".5: web passed with no version yet: taken again when its version is written") {
@@ -171,14 +206,14 @@ func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) {
key, _ := mwc.WantKey(node, "web") key, _ := mwc.WantKey(node, "web")
raw, got := wantsKV.values[key] raw, got := wantsKV.values[key]
if got != passed { if got != passed {
t.Errorf("passed %v: a want on %s written = %v", passed, node, got) t.Errorf("%s: a want on %s written = %v", c.name, node, got)
continue continue
} }
if !passed { if !passed {
continue continue
} }
if w, err := mwc.DecodeWant(raw); err != nil || w.Fp != fp || w.Version != "0.1.2" || w.Pipeline != trunkBranch+".5" || w.Rank != 2 { if w, err := mwc.DecodeWant(raw); err != nil || w.Fp != fp || w.Version != "0.1.2" || w.Pipeline != trunkBranch+".5" || w.Rank != 2 || w.Run != "205" {
t.Errorf("the want on %s = %+v (%v)", node, w, err) t.Errorf("%s: the want on %s = %+v (%v)", c.name, node, w, err)
} }
} }
} }
@@ -206,8 +241,25 @@ func TestARegistrationNamesTheDefaultBranch(t *testing.T) {
if woken == 0 || endsKept() != 1 || e.branchOf("web", "") != "beta" || e.branchOf("other", "") != trunkBranch { if woken == 0 || endsKept() != 1 || e.branchOf("web", "") != "beta" || e.branchOf("other", "") != trunkBranch {
t.Errorf("ends kept %d, default branch %q: an unwatched branch's end stayed, or the default is wrong", endsKept(), e.branchOf("web", "")) t.Errorf("ends kept %d, default branch %q: an unwatched branch's end stayed, or the default is wrong", endsKept(), e.branchOf("web", ""))
} }
if tg, ok := e.target("web", ""); !ok || tg.Fp != "fp2" { if tg, ok := e.target("web", ""); !ok || tg.Fp != "fp2" || tg.Seq != 205 {
t.Errorf("the default branch's target = %+v %v", tg, ok) t.Errorf("the default branch's target = %+v %v, want fp2 at seq 205", tg, ok)
}
// H-A-504 second addendum: an end kept without a sequence (before pipeline-ended said it) writes no want, said once.
raw, rev, _ := st.get(endKey("web", "beta"))
var old End
_ = json.Unmarshal(raw, &old)
old.Seq = 0
raw, _ = json.Marshal(old)
_ = st.swap(endKey("web", "beta"), raw, rev)
var said []string
e.logf = func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }
for range 2 {
if tg, ok := e.target("web", ""); ok {
t.Errorf("an end kept without seq is the target %+v", tg)
}
}
if len(said) != 1 || !strings.Contains(said[0], "beta.5") || !strings.Contains(said[0], "end-again") {
t.Errorf("an end kept without seq said %q, want once, naming the pipeline and end-again", said)
} }
e.registered(mpcat.Registration{Module: "web"}, true) e.registered(mpcat.Registration{Module: "web"}, true)
if endsKept() != 0 { if endsKept() != 0 {
@@ -98,8 +98,8 @@ func newOrderFixture(t *testing.T, mods []orderMod, history ...map[string]string
_, _ = p.ends.take(ended(trunkBranch, 1, mpr.PipelineEndedOutcomePassed, mover(m.name, m.trunk, "0.1.1", 1, mpr.StepResultOutcomePassed))) _, _ = p.ends.take(ended(trunkBranch, 1, mpr.PipelineEndedOutcomePassed, mover(m.name, m.trunk, "0.1.1", 1, mpr.StepResultOutcomePassed)))
wkey, _ := mwc.WantKey("ace", m.name) wkey, _ := mwc.WantKey("ace", m.name)
old, _ := mwc.EncodeWant(mwc.Want{Fp: m.run, Self: true}) old, _ := mwc.EncodeWant(mwc.Want{Fp: m.run, Self: true})
p.w.put(buckets.Wants(), wkey, old)
f.wants.values[wkey] = old f.wants.values[wkey] = old
p.w.putEntry(buckets.Wants(), wkey, old, f.wants.revision(wkey), time.Now()) // as the watch hands it, with its revision
} }
composes(t, p.w, "ace", digest) composes(t, p.w, "ace", digest)
values, err := mmac.AssignmentsValues(pl) values, err := mmac.AssignmentsValues(pl)
@@ -181,6 +181,7 @@ func (p *passer) putWorld(node, module string, put puts.Put, manifest catalogue.
if e, ok := p.w.ends.endOf(module, put.FP); ok { // the build's end heard (A-181): none heard, no state if e, ok := p.w.ends.endOf(module, put.FP); ok { // the build's end heard (A-181): none heard, no state
w.Build, w.BuildWords = e.Outcome, e.Error w.Build, w.BuildWords = e.Outcome, e.Error
} }
w.Version, _ = p.w.releasedOf(module, put.FP) // matched by its build's parts, as the pass matches a mover's (H-A-490 addendum)
w.Composed, w.Granted = p.composedFor(node, module, put.FP) w.Composed, w.Granted = p.composedFor(node, module, put.FP)
if d := w.Composed; d != nil { if d := w.Composed; d != nil {
policy := d.Policy policy := d.Policy
@@ -6,12 +6,14 @@ import (
"fmt" "fmt"
"slices" "slices"
"sort" "sort"
"strconv"
"strings" "strings"
"time" "time"
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/pipelinekey"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views" "git.novox.be/novox/mesh-sdk/go/views"
@@ -58,10 +60,16 @@ type tierProgress struct {
// tierKey is the key of pipeline's tier progress; pipeline is the runner's key `<branch>.<source>`, its branch escaped. // tierKey is the key of pipeline's tier progress; pipeline is the runner's key `<branch>.<source>`, its branch escaped.
func tierKey(pipeline string) string { return tierPrefix + pipeline } func tierKey(pipeline string) string { return tierPrefix + pipeline }
// isTierKey says whether a key of the state written is a pipeline's tier progress: three parts, the first `pipeline` (a module's // isTierKey says whether a key of the state written is a pipeline's tier progress: `pipeline.` and a pipeline's key of any form
// end has two). // the runner's seat defines, read by the one parse (design 47 H2 H-A-485), so an again pipeline's progress is one as a take-in's
// is (a module's end, `<module>.<branch>`, is none).
func isTierKey(key string) bool { func isTierKey(key string) bool {
return strings.HasPrefix(key, tierPrefix) && strings.Count(key, ".") == 2 rest, ok := strings.CutPrefix(key, tierPrefix)
if !ok {
return false
}
_, err := pipelinekey.Parse(rest)
return err == nil
} }
// startTiers writes the tier progress of a passed pipeline, holding every passed mover, versioned or not, its first tier the // startTiers writes the tier progress of a passed pipeline, holding every passed mover, versioned or not, its first tier the
@@ -166,11 +174,11 @@ func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []st
continue continue
} }
pipeline := strings.TrimPrefix(key, tierPrefix) pipeline := strings.TrimPrefix(key, tierPrefix)
branchEsc, number, _ := strings.Cut(pipeline, ".") pk, err := pipelinekey.Parse(pipeline)
branch, err := keys.UnescapeName(branchEsc)
if err != nil { if err != nil {
continue continue
} }
branch, number := pk.Branch, strconv.FormatInt(pk.Revision, 10)
for { for {
t, rev, ok := p.ends.tiersOf(pipeline) t, rev, ok := p.ends.tiersOf(pipeline)
if !ok { if !ok {
@@ -28,7 +28,12 @@ import (
// tier-bound: the finding tier-late names it and its machine, pipeline-wanted says tier-late, and no consumer want is written. // tier-bound: the finding tier-late names it and its machine, pipeline-wanted says tier-late, and no consumer want is written.
func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) { func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64) db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
for _, runs := range []bool{true, false} { // H-A-485: a pipeline started again at the head, keyed `<branch>.<revision>.again.<n>`, moves tier by tier as a take-in's does.
for _, c := range []struct {
runs bool
pipeline string
}{{true, trunkBranch + ".5"}, {false, trunkBranch + ".5"}, {true, trunkBranch + ".5.again.2"}, {false, trunkBranch + ".5.again.2"}} {
runs, pipeline := c.runs, c.pipeline
start := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC) start := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC)
now := start now := start
wantsKV := &memKV{values: map[string][]byte{}} wantsKV := &memKV{values: map[string][]byte{}}
@@ -41,7 +46,7 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
var said []meshwants.PipelineWanted var said []meshwants.PipelineWanted
p.publishWants = func(event string, body any, _ string) error { p.publishWants = func(event string, body any, _ string) error {
if b, ok := body.(meshwants.PipelineWantedEvent); ok { if b, ok := body.(meshwants.PipelineWantedEvent); ok {
if event != "pipeline-wanted."+trunkBranch+".5" { if event != "pipeline-wanted."+pipeline {
t.Errorf("pipeline-wanted said as %s", event) t.Errorf("pipeline-wanted said as %s", event)
} }
said = append(said, b) said = append(said, b)
@@ -65,7 +70,7 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
// The pipeline of revision 5 (its key's number) of source 4: a re-pin's revision (H-A-213, H-A-216). // The pipeline of revision 5 (its key's number) of source 4: a re-pin's revision (H-A-213, H-A-216).
e := ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("db", db, "0.2.0", 1, mpr.StepResultOutcomePassed), e := ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("db", db, "0.2.0", 1, mpr.StepResultOutcomePassed),
mover("web", web, "0.1.2", 2, mpr.StepResultOutcomePassed)) mover("web", web, "0.1.2", 2, mpr.StepResultOutcomePassed))
e.Source = 4 e.Source, e.Pipeline = 4, pipeline
if _, err := p.ends.take(e); err != nil { if _, err := p.ends.take(e); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -76,7 +81,7 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
} }
p.wants(context.Background()) p.wants(context.Background())
if !wanted("g14", "db") || !wanted("ace", "db") || wanted("g14", "web") || wanted("ace", "web") { if !wanted("g14", "db") || !wanted("ace", "db") || wanted("g14", "web") || wanted("ace", "web") {
t.Fatalf("runs %v: tier 1 alone is not what is wanted first: %v", runs, wantsKV.values) t.Fatalf("%s runs %v: tier 1 alone is not what is wanted first: %v", pipeline, runs, wantsKV.values)
} }
if runs { if runs {
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db}) raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db})
@@ -86,15 +91,15 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
now = start.Add(time.Minute) now = start.Add(time.Minute)
p.wants(context.Background()) p.wants(context.Background())
if !wanted("g14", "web") || !wanted("ace", "web") { if !wanted("g14", "web") || !wanted("ace", "web") {
t.Fatalf("the consumer's want is not written once its provider runs: %v", wantsKV.values) t.Fatalf("%s: the consumer's want is not written once its provider runs: %v", pipeline, wantsKV.values)
} }
raw, _ = json.Marshal(nodeengine.Running{Node: "g14", Module: "web", Fingerprint: web}) raw, _ = json.Marshal(nodeengine.Running{Node: "g14", Module: "web", Fingerprint: web})
_ = p.w.hearRunning("running.g14.web", raw) _ = p.w.hearRunning("running.g14.web", raw)
p.wants(context.Background()) p.wants(context.Background())
if len(said) != 1 || said[0].Outcome != meshwants.PipelineWantedOutcomeRunning || said[0].Revision != 5 || said[0].Source != 4 || len(findings) != 0 { if len(said) != 1 || said[0].Outcome != meshwants.PipelineWantedOutcomeRunning || said[0].Revision != 5 || said[0].Source != 4 || len(findings) != 0 {
t.Errorf("every tier runs: said %+v, findings %v", said, findings) t.Errorf("%s: every tier runs: said %+v, findings %v", pipeline, said, findings)
} }
if _, _, ok := p.ends.tiersOf(trunkBranch + ".5"); ok { if _, _, ok := p.ends.tiersOf(pipeline); ok {
t.Error("the tier progress stands after every tier ran") t.Error("the tier progress stands after every tier ran")
} }
continue continue
@@ -107,7 +112,7 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
now = start.Add(30 * time.Minute) now = start.Add(30 * time.Minute)
p.wants(context.Background()) p.wants(context.Background())
p.wants(context.Background()) p.wants(context.Background())
f, ok := findings["delivery."+assign.KeyID(trunkBranch+".5")+".tier-late"] f, ok := findings["delivery."+assign.KeyID(pipeline)+".tier-late"]
if !ok || !strings.Contains(f.Summary, "db on g14") || strings.Contains(f.Summary, "ace") { if !ok || !strings.Contains(f.Summary, "db on g14") || strings.Contains(f.Summary, "ace") {
t.Errorf("tier-late is not raised naming db on g14 alone: %v", findings) t.Errorf("tier-late is not raised naming db on g14 alone: %v", findings)
} }
@@ -116,7 +121,7 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
t.Errorf("pipeline-wanted tier-late is not said once, naming revision 5 of source 4: %+v", said) t.Errorf("pipeline-wanted tier-late is not said once, naming revision 5 of source 4: %+v", said)
} }
// A tier progress kept before it held its source says the key's number as both (H-A-216). // A tier progress kept before it held its source says the key's number as both (H-A-216).
p.sayPipelineWanted(trunkBranch+".5", trunkBranch, "5", 0, meshwants.PipelineWantedOutcomeRunning, nil) p.sayPipelineWanted(pipeline, trunkBranch, "5", 0, meshwants.PipelineWantedOutcomeRunning, nil)
if len(said) != 2 || said[1].Revision != 5 || said[1].Source != 5 { if len(said) != 2 || said[1].Revision != 5 || said[1].Source != 5 {
t.Errorf("a progress with no source: said %+v, want revision and source 5", said) t.Errorf("a progress with no source: said %+v, want revision and source 5", said)
} }
@@ -417,6 +417,7 @@ func serveTools() error {
tools = append(tools, whyTools(runtimeStore{})...) tools = append(tools, whyTools(runtimeStore{})...)
tools = append(tools, askAgainTools(runtimeStore{}, stdio.Ask, time.Now)...) tools = append(tools, askAgainTools(runtimeStore{}, stdio.Ask, time.Now)...)
tools = append(tools, wantDropTools(runtimeStore{}, stdio.Ask)...) tools = append(tools, wantDropTools(runtimeStore{}, stdio.Ask)...)
tools = append(tools, assignmentDropTools(runtimeStore{}, stdio.Ask, watchedModules(stdio.Ask))...) // a retired module's assignment key (H-A-509)
tools = append(tools, asksTools(stdio.QueueWaiting, stdio.State(process.TakenState), stdio.Ask)...) // the seat's work queue (§777) tools = append(tools, asksTools(stdio.QueueWaiting, stdio.State(process.TakenState), stdio.Ask)...) // the seat's work queue (§777)
tools = append(tools, keepNowTools(stdio.Ask)...) tools = append(tools, keepNowTools(stdio.Ask)...)
tools = append(tools, validateBeforeTools(runtimeStore{})...) // what a validate step did not count (§814) // the keeping by hand (§813 (2)) tools = append(tools, validateBeforeTools(runtimeStore{})...) // what a validate step did not count (§814) // the keeping by hand (§813 (2))
@@ -75,7 +75,7 @@ func (r *compositionRun) validate(ctx context.Context, id string, step meshwants
return couldNotRun("the validate run " + key + " is not joined: " + err.Error()) return couldNotRun("the validate run " + key + " is not joined: " + err.Error())
} }
if j.started { if j.started {
go r.startValidate(ctx, key, j.run, step) go r.startValidate(r.own, key, j.run, step) // on the assigner's own context (H-A-630 (3))
} }
return r.readValidate(ctx, key, step) return r.readValidate(ctx, key, step)
} }
@@ -92,8 +92,7 @@ func (r *compositionRun) resumeValidate(ctx context.Context, _ string, step mesh
// readValidate waits for the end of the validate run of key and judges the step from it. // readValidate waits for the end of the validate run of key and judges the step from it.
func (r *compositionRun) readValidate(ctx context.Context, key string, step meshwants.StepRun) stepOutcome { func (r *compositionRun) readValidate(ctx context.Context, key string, step meshwants.StepRun) stepOutcome {
setShared(ctx, r.runs.sharedOf([]string{key}, nil)) setShared(ctx, r.runs.sharedOf([]string{key}, nil))
setPhase(ctx, meshwants.StepProgressEventPhaseRun) run := r.runs.awaitEach(ctx, []string{key}, r.sayingWaits(ctx, "the validate step of "+step.Module))[key]
run := r.runs.await(ctx, []string{key})[key]
setPhase(ctx, meshwants.StepProgressEventPhaseReport) setPhase(ctx, meshwants.StepProgressEventPhaseReport)
out := r.judgeValidate(ctx, step, run) out := r.judgeValidate(ctx, step, run)
out.Shared = r.runs.sharedOf([]string{key}, map[string]meshwants.CompositionRun{key: run}) out.Shared = r.runs.sharedOf([]string{key}, map[string]meshwants.CompositionRun{key: run})
@@ -288,6 +287,13 @@ func (r *compositionRun) startValidate(ctx context.Context, key string, run mesh
return return
} }
program.Package = validatorPackage program.Package = validatorPackage
pins, said, ok := r.awaitPins(ctx, key, ask, "the manifest validator's entry "+entry.Fp, pinsOfEntry(entry), publishersOf(half.Entries))
if !ok {
if said != "" { // else the run ended or was replaced while it waited, or the step's wait ended
couldNot(said)
}
return
}
seats, list, err := r.validateSeats(ctx, ask, half.Revision.Definitions) seats, list, err := r.validateSeats(ctx, ask, half.Revision.Definitions)
if err != nil { if err != nil {
couldNot(err.Error()) couldNot(err.Error())
@@ -321,20 +327,27 @@ func (r *compositionRun) startValidate(ctx context.Context, key string, run mesh
couldNot(err.Error()) couldNot(err.Error())
return return
} }
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool { waited := false
written, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
waited = false
if c.Ask != ask || c.Ended != nil { if c.Ask != ask || c.Ended != nil {
return false return false
} }
c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: entry.Fp} c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: entry.Fp}
c.Input = digest c.Input = digest
waited, c.Waits = c.Waits != nil, nil // its wait ends as its run ask is put (H-A-629 (1))
return true return true
}); err != nil { })
if err != nil {
couldNot("the run's program and input are not written: " + err.Error()) couldNot("the run's program and input are not written: " + err.Error())
return return
} }
if waited { // its readers wait for a build node again, no longer for the package's publish (H-A-632)
r.runs.sayWaitsAtPut(written)
}
a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(), a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(),
Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the manifest validator of " + step.Pipeline + " at " + program.Commit}, Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the manifest validator of " + step.Pipeline + " at " + program.Commit},
Packages: pinsOfEntry(entry)} // the validator is built against its entry's pins at the step's revision (H-A-203, H-A-192, H-A-205) Packages: pins} // the validator is built against its entry's pins at the step's revision, each empty one filled (H-A-203, H-A-192, H-A-205, H-A-628 (2))
if err := r.put(ctx, a); err != nil { if err := r.put(ctx, a); err != nil {
couldNot("its run ask " + ask + " is not put: " + err.Error()) couldNot("its run ask " + ask + " is not put: " + err.Error())
} }
@@ -12,6 +12,7 @@ import (
"time" "time"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -32,6 +33,8 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
indexer := meshcatalog.CatalogEntry{Module: "indexer", Repository: "novox/mesh-delivery", Commit: commitE3, Path: "modules/mesh-delivery-indexer", indexer := meshcatalog.CatalogEntry{Module: "indexer", Repository: "novox/mesh-delivery", Commit: commitE3, Path: "modules/mesh-delivery-indexer",
Fp: "src2:ix", Serves: []string{"seat:" + meshcatalog.Seat + ".revision"}, Manifest: map[string]any{"module": "indexer"}, ManifestDigest: "d-ix", Fp: "src2:ix", Serves: []string{"seat:" + meshcatalog.Seat + ".revision"}, Manifest: map[string]any{"module": "indexer"}, ManifestDigest: "d-ix",
Packages: map[string]string{"git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient": "v0.1.4"}} Packages: map[string]string{"git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient": "v0.1.4"}}
unpinned := indexer
unpinned.Packages = map[string]string{"git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient": "v0.1.4", "git.novox.be/novox/mesh-sdk/go": ""}
entry := func(module, digest string, edges ...meshcatalog.Edge) meshcatalog.CatalogEntry { entry := func(module, digest string, edges ...meshcatalog.Edge) meshcatalog.CatalogEntry {
return meshcatalog.CatalogEntry{Module: module, Manifest: map[string]any{"module": module, "d": digest}, ManifestDigest: digest, Edges: edges} return meshcatalog.CatalogEntry{Module: module, Manifest: map[string]any{"module": module, "d": digest}, ManifestDigest: digest, Edges: edges}
} }
@@ -41,7 +44,13 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
9: {indexer, entry("a", "d-a", meshcatalog.Edge{From: "a:x", To: "b:y", Kind: 3}, meshcatalog.Edge{From: "b:y", To: "a:x", Kind: 3}), entry("b", "d-b")}, 9: {indexer, entry("a", "d-a", meshcatalog.Edge{From: "a:x", To: "b:y", Kind: 3}, meshcatalog.Edge{From: "b:y", To: "a:x", Kind: 3}), entry("b", "d-b")},
3: {indexer}, 3: {indexer},
12: {indexer, entry("web", "d-web-2"), entry("db", "d-db")}, 12: {indexer, entry("web", "d-web-2"), entry("db", "d-db")},
// 1984/AC10: the validator's entry names mesh-sdk/go with no version, and mesh-sdk's build in the revision publishes it.
13: {unpinned, entry("web", "d-web-2"), entry("db", "d-db"), {Module: "mesh-sdk", Fp: "src2:sdk1",
Artifacts: []meshcatalog.Artifact{{Ref: "mesh-sdk:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "git.novox.be/novox/mesh-sdk/go"}}}}},
} }
revisions[14] = revisions[13] // H-A-630 (3): its validate run waits for mesh-sdk's publish
var sdkMu sync.Mutex
sdkUnpublished := false
// base is the newest kept revision below n, as the take-in names it; none below the first. Revision 12 names 7 with 8 to 11 // base is the newest kept revision below n, as the take-in names it; none below the first. Revision 12 names 7 with 8 to 11
// never kept, so a case before read as the number minus one could not run (H-A-154). // never kept, so a case before read as the number minus one could not run (H-A-154).
base := func(n int64) (b int64) { base := func(n int64) (b int64) {
@@ -74,6 +83,18 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
Definitions: defs}, Entries: entries}) Definitions: defs}, Entries: entries})
case seatDefinitionsKey: case seatDefinitionsKey:
return json.Marshal(meshcatalog.SeatDefinitionsAnswer{Found: true, Entry: &meshcatalog.SeatDefinitionsAnswerEntry{Seat: "s1", Digest: "sd", Definition: map[string]any{"seat": "s1"}}}) return json.Marshal(meshcatalog.SeatDefinitionsAnswer{Found: true, Entry: &meshcatalog.SeatDefinitionsAnswerEntry{Seat: "s1", Digest: "sd", Definition: map[string]any{"seat": "s1"}}})
case publishedVerbKey:
var in builds.PublishedInput
_ = json.Unmarshal(raw, &in)
if in != (builds.PublishedInput{Module: "mesh-sdk", Artifact: "mesh-sdk:go", Fingerprint: "src2:sdk1"}) {
return nil, errors.New("published asked of another build")
}
sdkMu.Lock()
defer sdkMu.Unlock()
if sdkUnpublished {
return json.Marshal(builds.PublishedAnswer{})
}
return json.Marshal(builds.PublishedAnswer{Published: true, Version: "0.1.36"})
} }
return nil, errors.New("no such verb " + key) return nil, errors.New("no such verb " + key)
} }
@@ -98,7 +119,16 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
var requests []composer.Request var requests []composer.Request
keeper := testKeeper(&objectsMem{objs: map[string][]byte{}}, time.Now) keeper := testKeeper(&objectsMem{objs: map[string][]byte{}}, time.Now)
runs := newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf) runs := newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf)
r := &compositionRun{runs: runs, keeper: keeper, reads: &compositionReads{}, call: call, callFile: callFile, now: time.Now, logf: t.Logf, var held []string // the wait-helds of the reader ask-left said, what each waits on and its id (H-A-630 (5), H-A-632)
runs.say = func(event string, body any, id string) error {
if w := body.(meshwants.Wait); event == meshwants.EventWaitHeld && strings.Contains(id, ".ask-left.") {
mu.Lock()
held = append(held, w.On+" ("+id+")")
mu.Unlock()
}
return nil
}
r := &compositionRun{runs: runs, keeper: keeper, reads: &compositionReads{}, call: call, callFile: callFile, own: context.Background(), now: time.Now, logf: t.Logf,
put: func(_ context.Context, a buildstep.StepAsk) error { put: func(_ context.Context, a buildstep.StepAsk) error {
body, err := keeper.body(a.Run.Input.Digest) body, err := keeper.body(a.Run.Input.Digest)
if err != nil { if err != nil {
@@ -217,4 +247,41 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
} else if web := requests[2].Cases[1].Manifests["web"]; len(requests[2].Cases[1].Manifests) != 3 || !strings.Contains(string(web.Raw), "d-web-2") { } else if web := requests[2].Cases[1].Manifests["web"]; len(requests[2].Cases[1].Manifests) != 3 || !strings.Contains(string(web.Raw), "d-web-2") {
t.Errorf("the case before of revision 12 is %+v, want base 7's manifests", requests[2].Cases[1].Manifests) t.Errorf("the case before of revision 12 is %+v, want base 7's manifests", requests[2].Cases[1].Manifests)
} }
// 1984/AC10 (H-A-628 (2), (5)): the validator's pin with no version is filled from mesh-builds' published of its publisher's
// build in the step's revision, never left out.
if o := r.validate(ctx, "ask-unpinned", step("web", 13)); o.Outcome != meshwants.StepEndedOutcomeFailed || len(asks) != 4 {
t.Errorf("a validator entry with an empty pin ended %+v (%d validator asks), want it judged", o, len(asks))
} else if got := asks[3].Packages; len(got) != 2 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.36" || got["git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"] != "v0.1.4" {
t.Errorf("the validator is built against the pins %v; want mesh-sdk/go at v0.1.36 from published beside its entry's", got)
}
// H-A-630 (3): the validate run waits for mesh-sdk's publish on the assigner's own context, so the step that started it, ended
// meanwhile, leaves it waiting: at the publish it is put and ends passed for the movers that read it.
sdkMu.Lock()
sdkUnpublished = true
sdkMu.Unlock()
journal := newLogLines()
r.logf = journal.logf
starting, stop := context.WithCancel(ctx)
left := make(chan stepOutcome, 1)
go func() { left <- r.validate(starting, "ask-left", step("web", 14)) }()
journal.await(t, "waits for package git.novox.be/novox/mesh-sdk/go", 1)
stop()
if o := <-left; o.Outcome != meshwants.StepEndedOutcomeCouldNotRun {
t.Errorf("the starting step stopped ended %+v", o)
}
sdkMu.Lock()
sdkUnpublished = false
sdkMu.Unlock()
runs.heardPublished("mesh-sdk:go")
key, _ := validateKeyOf(step("web", 14))
run := runs.awaitEach(ctx, []string{key}, nil)[key]
mu.Lock()
defer mu.Unlock()
if run.Ended == nil || run.Outcome != meshwants.CompositionRunOutcomePassed || len(asks) != 5 || asks[4].Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.36" {
t.Errorf("the validate run its starting step left ended %v %s %q with %d validator asks, want it put after the publish and passed", run.Ended, run.Outcome, run.Said, len(asks))
}
if len(held) < 2 || !strings.HasPrefix(held[len(held)-2], waitOnPublish+"git.novox.be/novox/mesh-sdk/go (") ||
!strings.HasPrefix(held[len(held)-1], waitOnBuildNode+" (") || !strings.HasSuffix(held[len(held)-1], ".held.put)") {
t.Errorf("the validate run's reader was said waiting %v; want mesh-sdk's publish, then a build node again at the put (H-A-632)", held)
}
} }
+1
View File
@@ -8,6 +8,7 @@ require (
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
github.com/nats-io/nats-server/v2 v2.11.17 github.com/nats-io/nats-server/v2 v2.11.17
@@ -34,6 +34,9 @@ type PutWorld struct {
Build, BuildWords string Build, BuildWords string
// Newest is the module's newest fingerprint at the trunk, which the builder builds by itself. // Newest is the module's newest fingerprint at the trunk, which the builder builds by itself.
Newest string Newest string
// Version is the version released at the put's fingerprint, matched by its build's parts as the pass matches a mover's;
// "" when none is released (design 47 H2 H-A-490 addendum).
Version string
// Composed is the composition of the module for the node at the fingerprint, as its writer holds it; nil when there is // Composed is the composition of the module for the node at the fingerprint, as its writer holds it; nil when there is
// none. Granted says the grant at the fingerprint names the node's accounts. Both are read, never asked for (clause 4). // none. Granted says the grant at the fingerprint names the node's accounts. Both are read, never asked for (clause 4).
Composed *ComposedDigest Composed *ComposedDigest
@@ -87,7 +90,10 @@ func StepPut(w PutWorld) PutNext {
if h := w.Have; h == nil || h.Fp != p.FP || h.Composed == "" { if h := w.Have; h == nil || h.Fp != p.FP || h.Composed == "" {
return say(puts.Refused, "%s runs %s at %s, and its have names no composition at that fingerprint, so the want cannot name what runs", w.Node, w.Module, fp) return say(puts.Refused, "%s runs %s at %s, and its have names no composition at that fingerprint, so the want cannot name what runs", w.Node, w.Module, fp)
} }
p.Composed = w.Have.Composed if w.Version == "" {
return say(puts.Refused, "no version released at %s: build or release it first", fp)
}
p.Composed, p.Version = w.Have.Composed, w.Version
words := fmt.Sprintf("the want of %s on %s names %s, the build it runs now (composition %s), from its running statement; the builder's store is not asked", words := fmt.Sprintf("the want of %s on %s names %s, the build it runs now (composition %s), from its running statement; the builder's store is not asked",
w.Module, w.Node, fp, short(p.Composed)) w.Module, w.Node, fp, short(p.Composed))
if p.Hold { if p.Hold {
@@ -115,6 +121,14 @@ func StepPut(w PutWorld) PutNext {
default: default:
return say(puts.Build, "waits for the builder's build of %s at %s, which is %s", w.Module, fp, w.Build) return say(puts.Build, "waits for the builder's build of %s at %s, which is %s", w.Module, fp, w.Build)
} }
if p.Step != puts.Wanted && p.Step != puts.Holding {
// The want names the build's released version beside its fingerprint, which the node-engine composes from (H-A-490
// addendum): a build with none released is refused, never wanted by its fingerprint alone.
if w.Version == "" {
return say(puts.Refused, "no version released at %s: build or release it first", fp)
}
p.Version = w.Version
}
if w.Composed == nil || !w.Granted { if w.Composed == nil || !w.Granted {
missing := fmt.Sprintf("no composition of %s for %s at %s is written", w.Module, w.Node, fp) missing := fmt.Sprintf("no composition of %s for %s at %s is written", w.Module, w.Node, fp)
if w.Composed != nil { if w.Composed != nil {
@@ -212,9 +226,10 @@ func needsPerson(w PutWorld, d ComposedDigest) bool {
return d.Judgement == JudgedRecreates || d.Judgement == JudgedMovesData || d.Judgement == JudgedCannot return d.Judgement == JudgedRecreates || d.Judgement == JudgedMovesData || d.Judgement == JudgedCannot
} }
// PutWant is the want a put writes once it is wanted: the fingerprint, marked put, and held when it holds. // PutWant is the want a put writes once it is wanted: the fingerprint and the version released at it, marked put, and held when
// it holds.
func PutWant(p puts.Put) mwc.Want { func PutWant(p puts.Put) mwc.Want {
return mwc.Want{Fp: p.FP, Put: true, Hold: p.Hold, Words: "put: " + p.Why} return mwc.Want{Fp: p.FP, Version: p.Version, Put: true, Hold: p.Hold, Words: "put: " + p.Why}
} }
// PutOwns says what a put does to the node's want: owns says the rules pass over it, want the want it writes (nil: what // PutOwns says what a put does to the node's want: owns says the rules pass over it, want the want it writes (nil: what
@@ -3,6 +3,7 @@ package assign
import ( import (
"fmt" "fmt"
"slices" "slices"
"strconv"
"strings" "strings"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
@@ -28,6 +29,9 @@ type Target struct {
Version string Version string
Pipeline string Pipeline string
Rank int64 Rank int64
// Seq is the pipeline's sequence, the want's run in decimal (design 47 H2 §813 (1), H-A-504 addendum); 0 for a placement's
// build.
Seq int64
} }
// Module is what the want rule reads of one module: the nodes it is assigned to, the build each node's want names, the puts // Module is what the want rule reads of one module: the nodes it is assigned to, the build each node's want names, the puts
@@ -105,7 +109,7 @@ func Wants(m Module, wants map[string]mwc.Want) Outcome {
if !put && had && before.Put && before.Hold { if !put && had && before.Put && before.Hold {
// The want is the truth (ADR 0546 clause 5): a want marked put and held stands while its put is not heard; only a put // The want is the truth (ADR 0546 clause 5): a want marked put and held stands while its put is not heard; only a put
// heard released gives it back to the rule. // heard released gives it back to the rule.
p, put = puts.Put{FP: before.Fp, Hold: true, Why: strings.TrimPrefix(before.Words, "put: "), Step: puts.Holding}, true p, put = puts.Put{FP: before.Fp, Version: before.Version, Hold: true, Why: strings.TrimPrefix(before.Words, "put: "), Step: puts.Holding}, true
} }
if put { if put {
if want, owns := PutOwns(p); owns { if want, owns := PutOwns(p); owns {
@@ -123,6 +127,9 @@ func Wants(m Module, wants map[string]mwc.Want) Outcome {
continue continue
} }
next := mwc.Want{Fp: t.Fp, Version: t.Version, Pipeline: t.Pipeline, Rank: t.Rank, Self: m.selfOn(node)} next := mwc.Want{Fp: t.Fp, Version: t.Version, Pipeline: t.Pipeline, Rank: t.Rank, Self: m.selfOn(node)}
if t.Seq > 0 {
next.Run = strconv.FormatInt(t.Seq, 10)
}
if had && !before.Removed && !before.Put && before.Fp == t.Fp { if had && !before.Removed && !before.Put && before.Fp == t.Fp {
// The answers the want carries stay while its build does: a failed backup's (ADR 0539 §16), a held revert's, the yes. // The answers the want carries stay while its build does: a failed backup's (ADR 0539 §16), a held revert's, the yes.
next.Backup, next.Words, next.Revert, next.Yes, next.Release = before.Backup, before.Words, before.Revert, before.Yes, before.Release next.Backup, next.Words, next.Revert, next.Yes, next.Release = before.Backup, before.Words, before.Revert, before.Yes, before.Release
@@ -92,7 +92,7 @@ func TestAWantNamesTheNewestPassedVersion(t *testing.T) {
// want stands, marked put and held, and once released the rule writes the passed version again. // want stands, marked put and held, and once released the rule writes the passed version again.
func TestAPutOwnsItsNodesWant(t *testing.T) { func TestAPutOwnsItsNodesWant(t *testing.T) {
m := released() m := released()
put := puts.Put{FP: fNew, Hold: true, Why: "the bus's user list", Composed: dig(fNew)} put := puts.Put{FP: fNew, Version: "1.2.3", Hold: true, Why: "the bus's user list", Composed: dig(fNew)}
for _, c := range []struct { for _, c := range []struct {
name string name string
step string step string
@@ -100,7 +100,7 @@ func TestAPutOwnsItsNodesWant(t *testing.T) {
want *mwc.Want // nil: nothing written on ace want *mwc.Want // nil: nothing written on ace
}{ }{
{"waiting for the operator", puts.Person, wantedOld(), nil}, {"waiting for the operator", puts.Person, wantedOld(), nil},
{"wanted", puts.Wanted, wantedOld(), &mwc.Want{Fp: fNew, Put: true, Hold: true, Words: "put: the bus's user list"}}, {"wanted", puts.Wanted, wantedOld(), &mwc.Want{Fp: fNew, Version: "1.2.3", Put: true, Hold: true, Words: "put: the bus's user list"}},
{"holding, written already", puts.Holding, map[string]mwc.Want{"ace": PutWant(put)}, nil}, {"holding, written already", puts.Holding, map[string]mwc.Want{"ace": PutWant(put)}, nil},
{"released: the rule again", puts.Released, map[string]mwc.Want{"ace": PutWant(put)}, &mwc.Want{Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2}}, {"released: the rule again", puts.Released, map[string]mwc.Want{"ace": PutWant(put)}, &mwc.Want{Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2}},
{"not heard: a held want at an older fingerprint stands", "", map[string]mwc.Want{"ace": {Fp: fOld, Put: true, Hold: true, Words: "put: back"}}, nil}, {"not heard: a held want at an older fingerprint stands", "", map[string]mwc.Want{"ace": {Fp: fOld, Put: true, Hold: true, Words: "put: back"}}, nil},
@@ -144,7 +144,7 @@ func stepsOfAPut(t *testing.T) {
running := nodeengine.HaveByNodeModuleValue{Fp: fOld, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK} running := nodeengine.HaveByNodeModuleValue{Fp: fOld, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}
bus := func() PutWorld { bus := func() PutWorld {
return PutWorld{Node: "novox", Module: "nats", Put: base, Assigned: true, Bus: true, Build: builds.BuildDone, Newest: fNew, return PutWorld{Node: "novox", Module: "nats", Put: base, Assigned: true, Bus: true, Build: builds.BuildDone, Newest: fNew,
Composed: &d, Granted: true, Have: &running, Now: now} Version: "1.2.3", Composed: &d, Granted: true, Have: &running, Now: now}
} }
cases := []struct { cases := []struct {
name string name string
@@ -172,6 +172,16 @@ func stepsOfAPut(t *testing.T) {
w.Running = &nodeengine.Running{Node: "novox", Module: "nats", Fingerprint: fNew} w.Running = &nodeengine.Running{Node: "novox", Module: "nats", Fingerprint: fNew}
return w return w
}, puts.Refused, "names no composition", false, false, false}, }, puts.Refused, "names no composition", false, false, false},
// H-A-490 (addendum): a want names the build's released version, so a done build with none released is refused, and so
// is the build the node runs now when no release names its parts.
{"a done build with no released version: refused", func() PutWorld { w := bus(); w.Version = ""; return w }, puts.Refused, "no version released at", false, false, false},
{"the build the node runs now, no version released: refused", func() PutWorld {
w := bus()
w.Build, w.Newest, w.Version = "", fpOf('c'), ""
w.Running = &nodeengine.Running{Node: "novox", Module: "nats", Fingerprint: fNew}
w.Have = &nodeengine.HaveByNodeModuleValue{Fp: fNew, Composed: dig(fNew), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}
return w
}, puts.Refused, "build or release it first", false, false, false},
{"a failed build", func() PutWorld { w := bus(); w.Build, w.BuildWords = builds.BuildFailed, "go vet"; return w }, puts.Refused, "go vet", false, false, false}, {"a failed build", func() PutWorld { w := bus(); w.Build, w.BuildWords = builds.BuildFailed, "go vet"; return w }, puts.Refused, "go vet", false, false, false},
{"no composition yet: waits", func() PutWorld { w := bus(); w.Composed = nil; return w }, puts.Compose, "no composition of nats for novox", false, false, false}, {"no composition yet: waits", func() PutWorld { w := bus(); w.Composed = nil; return w }, puts.Compose, "no composition of nats for novox", false, false, false},
{"composed, grant not naming the node", func() PutWorld { w := bus(); w.Granted = false; return w }, puts.Compose, "does not name novox", false, false, false}, {"composed, grant not naming the node", func() PutWorld { w := bus(); w.Granted = false; return w }, puts.Compose, "does not name novox", false, false, false},
@@ -256,6 +266,9 @@ func stepsOfAPut(t *testing.T) {
} }
for _, c := range cases { for _, c := range cases {
next := StepPut(c.world()) next := StepPut(c.world())
if (next.Put.Step == puts.Wanted || next.Put.Step == puts.Holding) && c.world().Put.Step == puts.Asked && next.Put.Version != "1.2.3" {
t.Errorf("put, %s: its want names version %q, want the build's released 1.2.3", c.name, next.Put.Version)
}
if next.Put.Step != c.step || !strings.Contains(next.Put.Words, c.says) { if next.Put.Step != c.step || !strings.Contains(next.Put.Words, c.says) {
t.Errorf("put, %s: at %s, %q; want %s saying %q", c.name, next.Put.Step, next.Put.Words, c.step, c.says) t.Errorf("put, %s: at %s, %q; want %s saying %q", c.name, next.Put.Step, next.Put.Words, c.step, c.says)
} }
@@ -65,6 +65,9 @@ type Put struct {
V int `json:"v"` V int `json:"v"`
// FP is the fingerprint put, of the new form. // FP is the fingerprint put, of the new form.
FP string `json:"fp"` FP string `json:"fp"`
// Version is the version released at FP, which the want names beside it, once the put found it (design 47 H2 H-A-490
// addendum).
Version string `json:"version,omitempty"`
// Hold keeps the want at FP until released. // Hold keeps the want at FP until released.
Hold bool `json:"hold,omitempty"` Hold bool `json:"hold,omitempty"`
Why string `json:"why"` Why string `json:"why"`
@@ -116,8 +116,8 @@ func TestManifest(t *testing.T) {
// which lists and asks again what each node's engine reads. // which lists and asks again what each node's engine reads.
if !slices.Equal(m.Tools, []string{"assigner_put", "assigner_release", "assigner_puts", "assigner_waits", "assigner_inputs", "assigner_inputs_drop", "assigner_compositions", "assigner_compositions_drop", "assignments", "seat-holders", "wants", "asks", if !slices.Equal(m.Tools, []string{"assigner_put", "assigner_release", "assigner_puts", "assigner_waits", "assigner_inputs", "assigner_inputs_drop", "assigner_compositions", "assigner_compositions_drop", "assignments", "seat-holders", "wants", "asks",
"assigner_read_assignments", "assigner_read_seat_holders", "assigner_read_wants", "assigner_read_findings", "assigner_read_differences", "assigner_read_copies", "assigner_read_assignments", "assigner_read_seat_holders", "assigner_read_wants", "assigner_read_findings", "assigner_read_differences", "assigner_read_copies",
"assigner_first_views", "assigner_first_view_again", "assigner_engine_reads", "assigner_seat_list", "assigner_seat_list_again", "assigner_ask_again", "assigner_written", "assigner_why", "assigner_want_drop", "assigner_asks", "assigner_ask_drop", "assigner_keep_now", "assigner_validate_before"}) { "assigner_first_views", "assigner_first_view_again", "assigner_engine_reads", "assigner_seat_list", "assigner_seat_list_again", "assigner_ask_again", "assigner_written", "assigner_why", "assigner_want_drop", "assigner_assignment_drop", "assigner_asks", "assigner_ask_drop", "assigner_keep_now", "assigner_validate_before"}) {
t.Errorf("the assigner serves tools %v, want its three put tools, three first views, six read tools, assigner_engine_reads, the seat list's two (ADR 0636 §7) assigner_ask_again (ADR 0668 §5) and assigner_why (design 47 G A-439)", m.Tools) t.Errorf("the assigner serves tools %v, want its three put tools, three first views, six read tools, assigner_engine_reads, the seat list's two (ADR 0636 §7) assigner_ask_again (ADR 0668 §5), assigner_why (design 47 G A-439) and assigner_assignment_drop after assigner_want_drop (design 47 H2 H-A-509)", m.Tools)
} }
if m.RunsAs != m.Module || m.SecretsOwner != m.RunsAs { if m.RunsAs != m.Module || m.SecretsOwner != m.RunsAs {
t.Errorf("runs-as = %q: the bundle runs on the assigner's own account (ADR 0621 §1)", m.RunsAs) t.Errorf("runs-as = %q: the bundle runs on the assigner's own account (ADR 0621 §1)", m.RunsAs)
@@ -153,11 +153,12 @@ func TestManifest(t *testing.T) {
// issue 1966 note 151: and the teller's ask-ended, its subject the one the assigner hears; §389: the watchman's machine-away // issue 1966 note 151: and the teller's ask-ended, its subject the one the assigner hears; §389: the watchman's machine-away
// and machine-back, read whole at its start. A1/AC1 (design 47 H §750, §764): no version-delivered, delivery-waits, // and machine-back, read whole at its start. A1/AC1 (design 47 H §750, §764): no version-delivered, delivery-waits,
// delivered-again or assigner_delivered_again: a want waits on no dependency's delivery. // delivered-again or assigner_delivered_again: a want waits on no dependency's delivery.
if !slices.Equal(m.Consumes, []string{"mesh-conditions.findings-asked", "mesh-conditions.condition-raised", "mesh-conditions.condition-changed", "mesh-conditions.condition-cleared", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-catalog.version-released", "mesh-watchdogs.machine-away", "mesh-watchdogs.machine-back", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", builds.BuilderModule + "." + builds.BuildsStreamEvents, buckets.TellerModule + "." + tellerevents.AskEnded, buckets.TellerModule + ".views." + buckets.AnswersState, "mesh-pipeline-runner.pipeline-ended", "node-build-go.step-ended", "node-build-go.ask-taken", "node-build-go.step-progress", "node-engine.manifest-reads-changed", "node-engine.running"}) { if !slices.Equal(m.Consumes, []string{"mesh-conditions.findings-asked", "mesh-conditions.condition-raised", "mesh-conditions.condition-changed", "mesh-conditions.condition-cleared", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-catalog.version-released", "mesh-watchdogs.machine-away", "mesh-watchdogs.machine-back", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", builds.BuilderModule + "." + builds.BuildsStreamEvents, "mesh-builds.package-published", buckets.TellerModule + "." + tellerevents.AskEnded, buckets.TellerModule + ".views." + buckets.AnswersState, "mesh-pipeline-runner.pipeline-ended", "node-build-go.step-ended", "node-build-go.ask-taken", "node-build-go.step-progress", "node-engine.manifest-reads-changed", "node-engine.running"}) {
t.Errorf("consumes = %v, want the catalog half's revisions (design 47 G §195), the teller's ask-ended, the engines' reads changed and what they run", m.Consumes) t.Errorf("consumes = %v, want the catalog half's revisions (design 47 G §195), the teller's ask-ended, the engines' reads changed and what they run", m.Consumes)
} }
if want := []string{"mesh-delivery-indexer.manifests", "mesh-delivery-indexer.modules", if want := []string{"mesh-delivery-indexer.manifests", "mesh-delivery-indexer.modules",
buckets.TellerModule + "." + buckets.AnswersReadTool, // A-175, A-178: the teller's answers' first view buckets.TellerModule + "." + buckets.AnswersReadTool, // A-175, A-178: the teller's answers' first view
"seat:mesh-builds.published", // design 47 H2 H-A-628 (2), H-A-328: a run's empty pin filled from its publisher's build (1984/AC9, AC10)
"seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.revision", "seat:mesh-catalog.seat-definitions", // ADR 0636 §4: the seat list "seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.revision", "seat:mesh-catalog.seat-definitions", // ADR 0636 §4: the seat list
"seat:mesh-catalog.seat-list", // design 47 H2 H-A-443: the validate step's trunk seat list, in chunks "seat:mesh-catalog.seat-list", // design 47 H2 H-A-443: the validate step's trunk seat list, in chunks
"seat:mesh-conditions.conditions", // design 47 G §706: the conditions read at each judging of an outside wait "seat:mesh-conditions.conditions", // design 47 G §706: the conditions read at each judging of an outside wait
@@ -184,9 +185,13 @@ func TestManifest(t *testing.T) {
} }
file, _ := os.ReadFile("module.json") file, _ := os.ReadFile("module.json")
if err := json.Unmarshal(file, &raw); err != nil || raw.Config["outside-wait-minutes"].Default != float64(30) || raw.Config["outside-settle-seconds"].Default != float64(90) || if err := json.Unmarshal(file, &raw); err != nil || raw.Config["outside-wait-minutes"].Default != float64(30) || raw.Config["outside-settle-seconds"].Default != float64(90) ||
raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 15 || raw.Config["tier-bound"].Default != float64(30) || raw.Config["entry-asks"].Default != float64(5) || raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 17 || raw.Config["tier-bound"].Default != float64(30) || raw.Config["entry-asks"].Default != float64(5) ||
raw.Config["composition-runs-cap-mib"].Default != float64(16) || raw.Config["composition-runs-kept"].Default != "24h" || raw.Config["composition-runs-cap-mib"].Default != float64(16) || raw.Config["composition-runs-kept"].Default != "24h" ||
raw.Config["composition-step-bound"].Default != "30m" || raw.Config["run-untaken-bound"].Default != "24h" || raw.Config["blame-tries"].Default != float64(20) || raw.Config["composition-step-bound"].Default != "30m" || raw.Config["run-untaken-bound"].Default != "24h" || raw.Config["blame-tries"].Default != float64(20) ||
// design 47 H2 H-A-628 (3): the bound of a run's wait for a package's publish, the builder's default
raw.Config["package-wait-minutes"].Default != float64(10) ||
// design 47 H2 H-A-635: the bound a pass runs before it says which phase it is in
raw.Config["pass-stall-seconds"].Default != float64(60) ||
// design 47 H2 §775, H-A-381 (2): the taken key's bound and the kept-call pace, runtime settings // design 47 H2 §775, H-A-381 (2): the taken key's bound and the kept-call pace, runtime settings
raw.Config["ask-taken-bound"].Default != "10m" || raw.Config["kept-call-pace-first"].Default != "1s" || raw.Config["kept-call-pace-max"].Default != "30s" || raw.Config["compose-ask-bound"].Default != "10s" || raw.Config["keeping-retry"].Default != "30s" { raw.Config["ask-taken-bound"].Default != "10m" || raw.Config["kept-call-pace-first"].Default != "1s" || raw.Config["kept-call-pace-max"].Default != "30s" || raw.Config["compose-ask-bound"].Default != "10s" || raw.Config["keeping-retry"].Default != "30s" {
t.Errorf("config = %+v (%v), want outside-wait-minutes of 30, outside-settle-seconds of 90 and ask-operator-for of take-off,remove-node,stops (A-425a)", raw.Config, err) t.Errorf("config = %+v (%v), want outside-wait-minutes of 30, outside-settle-seconds of 90 and ask-operator-for of take-off,remove-node,stops (A-425a)", raw.Config, err)
@@ -201,8 +206,10 @@ func TestManifest(t *testing.T) {
{"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE", "${dir:state}/composition-step-bound", "composition-step-bound"}, {"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE", "${dir:state}/composition-step-bound", "composition-step-bound"},
{"MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE", "${dir:state}/run-untaken-bound", "run-untaken-bound"}, {"MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE", "${dir:state}/run-untaken-bound", "run-untaken-bound"},
{"MESH_ASSIGNER_BLAME_TRIES_FILE", "${dir:state}/blame-tries", "blame-tries"}, {"MESH_ASSIGNER_BLAME_TRIES_FILE", "${dir:state}/blame-tries", "blame-tries"},
{"MESH_ASSIGNER_TIER_BOUND_FILE", "${dir:state}/tier-bound", "tier-bound"}, // design 47 H §751 {"MESH_ASSIGNER_PACKAGE_WAIT_FILE", "${dir:state}/package-wait-minutes", "package-wait-minutes"}, // design 47 H2 H-A-628 (3)
{"MESH_ASSIGNER_ENTRY_ASKS_FILE", "${dir:state}/entry-asks", "entry-asks"}, // design 47 H H-A-60 {"MESH_ASSIGNER_PASS_STALL_FILE", "${dir:state}/pass-stall-seconds", "pass-stall-seconds"}, // design 47 H2 H-A-635
{"MESH_ASSIGNER_TIER_BOUND_FILE", "${dir:state}/tier-bound", "tier-bound"}, // design 47 H §751
{"MESH_ASSIGNER_ENTRY_ASKS_FILE", "${dir:state}/entry-asks", "entry-asks"}, // design 47 H H-A-60
} { } {
if !strings.Contains(string(file), `"`+f.env+`": "`+f.path+`"`) || !strings.Contains(string(file), `"path": "`+f.path+`"`) || if !strings.Contains(string(file), `"`+f.env+`": "`+f.path+`"`) || !strings.Contains(string(file), `"path": "`+f.path+`"`) ||
!strings.Contains(string(file), `"content": "${config:`+f.key+`}"`) { !strings.Contains(string(file), `"content": "${config:`+f.key+`}"`) {
+38 -1
View File
@@ -56,6 +56,7 @@
"mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed", "mesh-catalog.seat-definition-removed",
"mesh-delivery-builder.build.ended.**", "mesh-delivery-builder.build.ended.**",
"mesh-builds.package-published",
"mesh-delivery-teller.ask-ended", "mesh-delivery-teller.ask-ended",
"mesh-delivery-teller.views.answers", "mesh-delivery-teller.views.answers",
"mesh-pipeline-runner.pipeline-ended", "mesh-pipeline-runner.pipeline-ended",
@@ -69,6 +70,7 @@
"mesh-delivery-indexer.manifests", "mesh-delivery-indexer.manifests",
"mesh-delivery-indexer.modules", "mesh-delivery-indexer.modules",
"mesh-delivery-teller.teller_read_answers", "mesh-delivery-teller.teller_read_answers",
"seat:mesh-builds.published",
"seat:mesh-catalog.entry", "seat:mesh-catalog.entry",
"seat:mesh-catalog.registrations", "seat:mesh-catalog.registrations",
{"verb": "seat:mesh-catalog.revision", "fields": ["none-yet"]}, {"verb": "seat:mesh-catalog.revision", "fields": ["none-yet"]},
@@ -134,6 +136,7 @@
"assigner_written", "assigner_written",
"assigner_why", "assigner_why",
"assigner_want_drop", "assigner_want_drop",
"assigner_assignment_drop",
"assigner_asks", "assigner_asks",
"assigner_ask_drop", "assigner_ask_drop",
"assigner_keep_now", "assigner_keep_now",
@@ -228,6 +231,22 @@
"trusted": false, "trusted": false,
"default": "24h" "default": "24h"
}, },
"package-wait-minutes": {
"type": "number",
"description": "minutes a composition or validate run waits for the publish of a mesh package its entry names with no version, counted from the time its wait began, before it ends could not run naming the package (design 47 H2 H-A-628 (3), H-A-629 (3)); the builder's range and default.",
"minimum": 1,
"maximum": 120,
"trusted": false,
"default": 10
},
"pass-stall-seconds": {
"type": "number",
"description": "seconds a pass of the assigner may run before it says in the journal which phase it is in, and again at each further bound until it ends (design 47 H2 H-A-635).",
"minimum": 10,
"maximum": 600,
"trusted": false,
"default": 60
},
"blame-tries": { "blame-tries": {
"type": "number", "type": "number",
"description": "the most compositions a machine's composer makes to find the modules it blames, carried in the run's request as blame_tries (design 47 G section 721, A-466r).", "description": "the most compositions a machine's composer makes to find the modules it blames, carried in the run's request as blame_tries (design 47 G section 721, A-466r).",
@@ -367,6 +386,22 @@
"mode": "0600", "mode": "0600",
"content": "${config:run-untaken-bound}" "content": "${config:run-untaken-bound}"
}, },
{
"id": "package-wait-minutes",
"type": "file",
"path": "${dir:state}/package-wait-minutes",
"owner": "mesh-delivery-assigner",
"mode": "0600",
"content": "${config:package-wait-minutes}"
},
{
"id": "pass-stall-seconds",
"type": "file",
"path": "${dir:state}/pass-stall-seconds",
"owner": "mesh-delivery-assigner",
"mode": "0600",
"content": "${config:pass-stall-seconds}"
},
{ {
"id": "blame-tries", "id": "blame-tries",
"type": "file", "type": "file",
@@ -394,7 +429,9 @@
"MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "${dir:state}/composition-runs-kept", "MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "${dir:state}/composition-runs-kept",
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "${dir:state}/composition-step-bound", "MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "${dir:state}/composition-step-bound",
"MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "${dir:state}/run-untaken-bound", "MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "${dir:state}/run-untaken-bound",
"MESH_ASSIGNER_BLAME_TRIES_FILE": "${dir:state}/blame-tries" "MESH_ASSIGNER_BLAME_TRIES_FILE": "${dir:state}/blame-tries",
"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes",
"MESH_ASSIGNER_PASS_STALL_FILE": "${dir:state}/pass-stall-seconds"
}, },
"user": "mesh-delivery-assigner", "user": "mesh-delivery-assigner",
"health": { "health": {
@@ -19,7 +19,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/kept" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/kept"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
) )
@@ -240,9 +239,6 @@ type BuilderBuild struct {
// its id (novox/hq ADR 0525 §1; issue 1887 A4b): a builder that takes the key over at its start waits for those asks' // its id (novox/hq ADR 0525 §1; issue 1887 A4b): a builder that takes the key over at its start waits for those asks'
// steps and never puts them again. A reader that does not know the field reads the key as before. // steps and never puts them again. A reader that does not know the field reads the key as before.
Asks map[string]string `json:"asks,omitempty"` Asks map[string]string `json:"asks,omitempty"`
// Imports are, on a done key, the mesh packages the built programs import, as the build module answered them
// (BuildAnswer.Imports; novox/hq ADR 0593 §2): the builder carries them onto the build's end (BuildLogEntry.Imports).
Imports []string `json:"imports,omitempty"`
// Packages are, on a done key only, the mesh packages' versions its Go build was built with, by module path, the ones // Packages are, on a done key only, the mesh packages' versions its Go build was built with, by module path, the ones
// the registry gave a package the entry named with none included (H-A-207): the build step's end reports them, so the // the registry gave a package the entry named with none included (H-A-207): the build step's end reports them, so the
// runner asks the steps that waited for the pins with what the build was built against. A reader that does not know // runner asks the steps that waited for the pins with what the build was built against. A reader that does not know
@@ -272,9 +268,6 @@ func (b BuilderBuild) check() error {
if b.KeptOn != "" && b.State != BuildDone { if b.KeptOn != "" && b.State != BuildDone {
return fmt.Errorf("builds: a build is kept on a done key alone, this one is %s", b.State) return fmt.Errorf("builds: a build is kept on a done key alone, this one is %s", b.State)
} }
if err := trunk.CheckImports(b.Imports); err != nil {
return err
}
switch b.State { switch b.State {
case BuildQueued, BuildBuilding, BuildDone, BuildFailed: case BuildQueued, BuildBuilding, BuildDone, BuildFailed:
default: default:
+4 -12
View File
@@ -6,7 +6,6 @@ import (
"sort" "sort"
"time" "time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
) )
@@ -70,10 +69,6 @@ type BuildLogEntry struct {
// KeptOn is, at the end of a kept build, the build node that keeps it, once for the build (design 47 G §671): every // KeptOn is, at the end of a kept build, the build node that keeps it, once for the build (design 47 G §671): every
// artifact in Made is kept there, with its digest. A build not kept carries none. // artifact in Made is kept there, with its digest. A build not kept carries none.
KeptOn string `json:"kept-on,omitempty"` KeptOn string `json:"kept-on,omitempty"`
// Imports are, at a build's end, the mesh packages (import paths) the built programs import, their tests left out,
// sorted and each once, as the build module answered them (BuildAnswer.Imports; novox/hq ADR 0593 §2): the indexer
// keeps them on the module (KeptInputs2.Imports) when the build's fingerprint is the module's.
Imports []string `json:"imports,omitempty"`
// OutOfStep are, at a build's end, the generated files its test step found out of step with what their generator // OutOfStep are, at a build's end, the generated files its test step found out of step with what their generator
// writes, as the build module answered them (its test step's `out-of-step`): the indexer raises a finding naming them // writes, as the build module answered them (its test step's `out-of-step`): the indexer raises a finding naming them
// for a trunk build, and only a clean build of the same module clears it. A start or a narration names none. // for a trunk build, and only a clean build of the same module clears it. A start or a narration names none.
@@ -132,9 +127,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
switch { switch {
case e.Module == "" || e.FP == "" || e.At.IsZero() || e.Line == "": case e.Module == "" || e.FP == "" || e.At.IsZero() || e.Line == "":
return nil, fmt.Errorf("builds: a build's narration names its module, fingerprint, line and time") return nil, fmt.Errorf("builds: a build's narration names its module, fingerprint, line and time")
case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 || len(e.OutOfStep) > 0 || case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.OutOfStep) > 0 ||
e.Error != "" || e.Step != "": e.Error != "" || e.Step != "":
return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, import, file out of step, error or step") return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, file out of step, error or step")
} }
return json.Marshal(e) return json.Marshal(e)
case e.Event != BuildStartedEvent && e.Event != BuildEndedEvent: case e.Event != BuildStartedEvent && e.Event != BuildEndedEvent:
@@ -145,12 +140,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
return nil, fmt.Errorf("builds: a build log entry names its module, fingerprint, repository, commit, node and time") return nil, fmt.Errorf("builds: a build log entry names its module, fingerprint, repository, commit, node and time")
case e.Event == BuildEndedEvent && e.Outcome == "": case e.Event == BuildEndedEvent && e.Outcome == "":
return nil, fmt.Errorf("builds: a build's end names its outcome") return nil, fmt.Errorf("builds: a build's end names its outcome")
case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 || case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 ||
len(e.OutOfStep) > 0 || e.Error != "" || e.Step != ""): len(e.OutOfStep) > 0 || e.Error != "" || e.Step != ""):
return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, import, file out of step, error or step") return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, file out of step, error or step")
}
if err := trunk.CheckImports(e.Imports); err != nil {
return nil, err
} }
return json.Marshal(e) return json.Marshal(e)
} }
@@ -5,9 +5,12 @@ import (
"errors" "errors"
"strings" "strings"
"testing" "testing"
"time"
"mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/build"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
) )
@@ -54,3 +57,14 @@ func TestABuildSeatsStepsAreReadInItsHoldersState(t *testing.T) {
t.Errorf("a seat with no holder reads %v; want an error naming it", err) t.Errorf("a seat with no holder reads %v; want an error naming it", err)
} }
} }
// H-A-487: a build key's time is its entry's own write time, read with the key and no history.
func TestABuildKeysTimeIsItsEntrysOwnWriteTime(t *testing.T) {
at := time.Date(2026, 11, 22, 20, 45, 0, 0, time.UTC)
raw, rev, got, err := entryOf(func(key string) (*stdio.StateEntry, error) {
return &stdio.StateEntry{Key: key, Value: json.RawMessage(`{}`), Revision: 4, At: at}, nil
})("k")
if err != nil || string(raw) != "{}" || rev != 4 || !got.Equal(at) {
t.Errorf("entry = %s rev %d at %v (%v); want the entry's own write time %v", raw, rev, got, err, at)
}
}
@@ -41,10 +41,10 @@ type queueAsker func(key string, value []byte) (json.RawMessage, error)
// Tools are the builder's tools: stuck reads, askAgain writes the reasks value, queue writes a queues value and waits for // Tools are the builder's tools: stuck reads, askAgain writes the reasks value, queue writes a queues value and waits for
// the builder's read, buildAgain writes a reasks value of mode build and waits for the builder's answer. // the builder's read, buildAgain writes a reasks value of mode build and waits for the builder's answer.
// //
// builder_versions, asked by a name, answers also what the verb reserved answers for it (reserve; design 47 G §572): the // builder_versions answers from the reservations alone, what the verb reserved answers for a name (reserve; design 47 G §572,
// bundle calls the seat mesh-builds through its invokes, as any caller does. Nil answers none. // H §756): the bundle calls the seat mesh-builds through its invokes, as any caller does.
func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time, vs versions.Reader, func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time,
fw, of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool { of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool {
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) } str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
// handAct writes a reasks value of a versions hand act and answers the builder's answer, or its refusal as an error. // handAct writes a reasks value of a versions hand act and answers the builder's answer, or its refusal as an error.
handAct := func(key string, value []byte, err error) (any, error) { handAct := func(key string, value []byte, err error) (any, error) {
@@ -65,13 +65,6 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
return map[string]any{"key": key, "name": a.Name, "answer": a.Answer}, nil return map[string]any{"key": key, "name": a.Name, "answer": a.Answer}, nil
} }
return []stdio.Tool{ return []stdio.Tool{
{Name: versions.FloorAgainTool, Description: versions.FloorAgainDescription,
Input: map[string]any{"type": "object", "required": []string{"name", "why"}, "properties": map[string]any{
"name": map[string]any{"type": "string", "description": "the numbered name, <module>/<artifact>"},
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
Run: func(args map[string]any) (any, error) {
return handAct(build.NewFloorAgain(str(args, "name"), str(args, "why"), stdio.CallerOf(args), now()))
}},
{Name: versions.OldFormTool, Description: versions.OldFormDescription, {Name: versions.OldFormTool, Description: versions.OldFormDescription,
Input: map[string]any{"type": "object", "properties": map[string]any{ Input: map[string]any{"type": "object", "properties": map[string]any{
"drop": map[string]any{"type": "string", "description": "a retired node to drop from the count by hand"}, "drop": map[string]any{"type": "string", "description": "a retired node to drop from the count by hand"},
@@ -82,25 +75,13 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
} }
return versions.AnswerOldForm(of) return versions.AnswerOldForm(of)
}}, }},
{Name: versions.FloorWaitsTool, Description: versions.FloorWaitsDescription,
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) { return versions.AnswerFloorWaits(fw) }},
{Name: versions.VersionsTool, Description: versions.VersionsDescription, {Name: versions.VersionsTool, Description: versions.VersionsDescription,
Input: map[string]any{"type": "object", "required": []string{"name"}, "properties": map[string]any{ Input: map[string]any{"type": "object", "required": []string{"name"}, "properties": map[string]any{
"name": map[string]any{"type": "string", "description": "the package, image, bundle or archive name"}, "name": map[string]any{"type": "string", "description": "the package, image, bundle or archive name"},
"version": map[string]any{"type": "string", "description": "one version, to ask whether it is recorded"}, "version": map[string]any{"type": "string", "description": "one version, to ask whether it is recorded"},
"digest": map[string]any{"type": "string", "description": "with version: the digest the holder received"}}}, "digest": map[string]any{"type": "string", "description": "with version: the digest the holder received"}}},
Run: func(args map[string]any) (any, error) { Run: func(args map[string]any) (any, error) {
out, err := versions.AnswerVersions(context.Background(), vs, str(args, "name"), str(args, "version"), str(args, "digest")) return versions.AnswerVersions(str(args, "name"), str(args, "version"), str(args, "digest"), reserve)
if err != nil || reserve == nil {
return out, err
}
ra, err := reserve(out.Name, str(args, "version"))
if err != nil {
return nil, fmt.Errorf("the seat mesh-builds' reserved did not answer for %s: %w", out.Name, err)
}
out.Reserved = &ra
return out, nil
}}, }},
{Name: build.StuckTool, {Name: build.StuckTool,
Description: "Every build key that waits (building or queued), oldest first: its module, fingerprint, step words and since when, and each ask it " + Description: "Every build key that waits (building or queued), oldest first: its module, fingerprint, step words and since when, and each ask it " +
@@ -358,22 +339,6 @@ func main() {
a, err := build.DecodeReAsk(v) a, err := build.DecodeReAsk(v)
return err == nil && !a.Answered.IsZero() return err == nil && !a.Answered.IsZero()
}) })
vs := stdio.State(versions.State)
vr := versions.Reader{Keys: vs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := vs.Get(key)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}}
fs := stdio.State(versions.FloorWaitsState)
fr := versions.Reader{Keys: fs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := fs.Get(key)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}}
ofs := stdio.State(versions.OldFormState) ofs := stdio.State(versions.OldFormState)
ofr := versions.Reader{Keys: ofs.Keys, Get: func(key string) (json.RawMessage, bool, error) { ofr := versions.Reader{Keys: ofs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := ofs.Get(key) e, err := ofs.Get(key)
@@ -429,8 +394,8 @@ func main() {
var a meshbuilds.ReservedAnswer var a meshbuilds.ReservedAnswer
return a, json.Unmarshal(raw, &a) return a, json.Unmarshal(raw, &a)
} }
tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, vr, fr, ofr, reserve) tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, ofr, reserve)
tools = append(tools, buildTool(&build.BuildReader{Builds: read(stdio.State("builds")), Entry: entryOf(stdio.State("builds")), Asked: read(stdio.State("asked")), tools = append(tools, buildTool(&build.BuildReader{Builds: read(stdio.State("builds")), Entry: entryOf(stdio.State("builds").Get), Asked: read(stdio.State("asked")),
Newest: newestVia(stdio.Ask), Steps: r})) Newest: newestVia(stdio.Ask), Steps: r}))
tools = append(tools, reservedTools(rr, buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...) tools = append(tools, reservedTools(rr, buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
as := stdio.State(versions.ActedState) as := stdio.State(versions.ActedState)
@@ -481,13 +446,14 @@ func main() {
} }
} }
// entryOf reads a key with its revision and when it was written. // entryOf reads a key with its revision and when it was written, the entry's own write time: no key's history is read
func entryOf(s stdio.KeptState) func(key string) (json.RawMessage, uint64, time.Time, error) { // (design 47 H2 H-A-487).
func entryOf(get func(key string) (*stdio.StateEntry, error)) func(key string) (json.RawMessage, uint64, time.Time, error) {
return func(key string) (json.RawMessage, uint64, time.Time, error) { return func(key string) (json.RawMessage, uint64, time.Time, error) {
e, err := s.Get(key) e, err := get(key)
if err != nil || e == nil { if err != nil || e == nil {
return nil, 0, time.Time{}, err return nil, 0, time.Time{}, err
} }
return e.Value, e.Revision, written(s, key, e.Revision), nil return e.Value, e.Revision, e.At, nil
} }
} }
@@ -73,7 +73,7 @@ func publishQueueVia(ask func(key string, body any) (json.RawMessage, error)) fu
} }
} }
// publishActTools are builder_publish_drop and builder_publish_first (design 47 H2 §793): hand acts, recorded in the hand-act log // publishActTools are builder_publish_drop (design 47 H2 §793; builder_publish_first is retired, H-A-483 third addendum): hand acts, recorded in the hand-act log
// first, then written to reasks for the builder, which owns the work queue, to perform and answer. // first, then written to reasks for the builder, which owns the work queue, to perform and answer.
func publishActTools(ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool { func publishActTools(ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool {
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) } str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
@@ -108,7 +108,6 @@ func publishActTools(ask queueAsker, now func() time.Time, acts meshhandactsclie
} }
return []stdio.Tool{ return []stdio.Tool{
tool(versions.PublishDropTool, build.ModePublishDrop, versions.PublishDropDescription, "dropped the publish of"), tool(versions.PublishDropTool, build.ModePublishDrop, versions.PublishDropDescription, "dropped the publish of"),
tool(versions.PublishFirstTool, build.ModePublishFirst, versions.PublishFirstDescription, "put first the publish of"),
} }
} }
@@ -78,8 +78,8 @@ func TestAStateIsReadInOnePage(t *testing.T) {
} }
}) })
// Design 47 H2 §793, H-A-454: builder_publish_queue asks the seat mesh-builds' verb publish-queue, which the builder serves from // Design 47 H2 §793, H-A-454: builder_publish_queue asks the seat mesh-builds' verb publish-queue, which the builder serves from
// its own stream, and answers its counts, list and cap with the states beside them; builder_publish_drop and // its own stream, and answers its counts, list and cap with the states beside them; builder_publish_drop records the hand act
// builder_publish_first record the hand act first, then write their reasks value. // first, then writes its reasks value; builder_publish_first is retired (H-A-483, third addendum).
t.Run("the queue is the builder's verb publish-queue", func(t *testing.T) { t.Run("the queue is the builder's verb publish-queue", func(t *testing.T) {
var asked []string var asked []string
ask := func(key string, body any) (json.RawMessage, error) { ask := func(key string, body any) (json.RawMessage, error) {
@@ -123,7 +123,7 @@ func TestAStateIsReadInOnePage(t *testing.T) {
t.Errorf("asked %v, answered %+v (%v): want each holder asked in turn at its node, answered together, the silent one with why", asked, hs, err) t.Errorf("asked %v, answered %+v (%v): want each holder asked in turn at its node, answered together, the silent one with why", asked, hs, err)
} }
}) })
t.Run("drop and first record the hand act, then ask the builder", func(t *testing.T) { t.Run("drop records the hand act, then asks the builder; first is retired", func(t *testing.T) {
var order []string var order []string
ask := func(key string, value []byte) (json.RawMessage, error) { ask := func(key string, value []byte) (json.RawMessage, error) {
order = append(order, "ask "+key) order = append(order, "ask "+key)
@@ -141,8 +141,8 @@ func TestAStateIsReadInOnePage(t *testing.T) {
t.Fatalf("%s: %v", tool.Name, err) t.Fatalf("%s: %v", tool.Name, err)
} }
} }
if len(tools) != 2 || fmt.Sprint(order) != "[record ask publish-drop.5000000000 record ask publish-first.5000000000]" { if len(tools) != 1 || tools[0].Name != versions.PublishDropTool || fmt.Sprint(order) != "[record ask publish-drop.5000000000]" {
t.Errorf("tools %d, order %v: want each hand act recorded before its reasks value", len(tools), order) t.Errorf("tools %d, order %v: want builder_publish_drop alone, its hand act recorded before its reasks value", len(tools), order)
} }
if _, err := tools[0].Run(map[string]any{"module": "m", "why": "no version"}); err == nil { if _, err := tools[0].Run(map[string]any{"module": "m", "why": "no version"}); err == nil {
t.Error("a drop naming no version is not refused") t.Error("a drop naming no version is not refused")
@@ -28,7 +28,7 @@ func TestBuilderVersionsByNameCallsReserved(t *testing.T) {
called = append(called, name+"@"+version) called = append(called, name+"@"+version)
return want, nil return want, nil
} }
tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, none, none, reserve) tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, reserve)
for _, tl := range tools { for _, tl := range tools {
if tl.Name == versions.VersionsTool { if tl.Name == versions.VersionsTool {
out, err := tl.Run(map[string]any{"name": "@novox/mesh-sdk", "version": "0.1.2"}) out, err := tl.Run(map[string]any{"name": "@novox/mesh-sdk", "version": "0.1.2"})
@@ -9,12 +9,12 @@ import (
// ownBuckets are the buckets of the builder's own states, each `<module>_<state>` of the module its credential names, never // ownBuckets are the buckets of the builder's own states, each `<module>_<state>` of the module its credential names, never
// a constant (design 47 G A-296, §428). // a constant (design 47 G A-296, §428).
type ownBuckets struct { type ownBuckets struct {
versions, bounds, reserved, queue, acted, toolchainsHeard, instances string bounds, reserved, queue, acted, toolchainsHeard, instances string
} }
func ownBucketsOf(module string) ownBuckets { func ownBucketsOf(module string) ownBuckets {
return ownBuckets{ return ownBuckets{
versions: builds.StateBucket(module, versions.State), bounds: builds.StateBucket(module, versions.BoundsState), bounds: builds.StateBucket(module, versions.BoundsState),
reserved: builds.StateBucket(module, versions.ReservedState), queue: builds.StateBucket(module, versions.PublishQueueState), reserved: builds.StateBucket(module, versions.ReservedState), queue: builds.StateBucket(module, versions.PublishQueueState),
acted: builds.StateBucket(module, versions.ActedState), toolchainsHeard: builds.StateBucket(module, buildrun.ToolchainsHeardState), acted: builds.StateBucket(module, versions.ActedState), toolchainsHeard: builds.StateBucket(module, buildrun.ToolchainsHeardState),
instances: builds.StateBucket(module, instancesState), instances: builds.StateBucket(module, instancesState),
@@ -75,8 +75,6 @@ type catalogHalf struct {
halves map[string]*views.Follower halves map[string]*views.Follower
once sync.Once once sync.Once
ctx context.Context ctx context.Context
// floor is told each entry change: a floor whose tags or requirements were silent is asked again (design 47 G A-119).
floor func(context.Context)
// holders is told each entry change: a claim of a build seat may have moved (design 47 G A-82). // holders is told each entry change: a claim of a build seat may have moved (design 47 G A-82).
holders func() holders func()
} }
@@ -112,9 +110,6 @@ func (c *catalogHalf) Changed(ctx context.Context) func(branch, module string, e
c.logf("%v", err) c.logf("%v", err)
} }
c.b.Entry(ctx, origin, e) c.b.Entry(ctx, origin, e)
if c.floor != nil {
defer c.floor(ctx)
}
c.mu.Lock() c.mu.Lock()
was := c.named[module] was := c.named[module]
now := namesOf(e) now := namesOf(e)
@@ -1,12 +1,18 @@
package main package main
import ( import (
"encoding/json"
"errors" "errors"
"slices"
"sync"
"time" "time"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go" stdio "git.novox.be/novox/mesh-sdk/go"
"mesh-delivery-builder/internal/versions"
) )
// slowEventSetting is the setting slow-event (design 47 H2 §794; H-A-461 (2), P11): how long the handling of one heard event // slowEventSetting is the setting slow-event (design 47 H2 §794; H-A-461 (2), P11): how long the handling of one heard event
@@ -53,3 +59,79 @@ func takeEvent(m jetstream.Msg, takers []eventTaker, rest eventTaker, slow time.
logf("the event %s took %s to handle, over %s: %s took it", m.Subject(), took.Round(time.Millisecond), slow, part) logf("the event %s took %s to handle, over %s: %s took it", m.Subject(), took.Round(time.Millisecond), slow, part)
} }
} }
// eventWorkers hands each event of the builder's durable to a worker of its key (design 47 H2 H-A-514 addenda): the name the
// event carries (a registry seat's outcome's package name, a version-released's module), one shared worker for the events that
// name none. One key's events are handled in the order heard, the keys side by side, so a slow event of one name delays no
// other name's. A worker ends when its queue is empty. The builder holds no timer (ADR 0437 §8), so the events still waiting in
// a queue are said in progress to the bus each time its worker ends a handling, and none waits out the ack wait behind another.
type eventWorkers struct {
handle func(jetstream.Msg)
keyOf func(jetstream.Msg) string
mu sync.Mutex
queues map[string]*eventQueue
}
// eventQueue is one key's events not yet handled, the one handled now first.
type eventQueue struct{ msgs []jetstream.Msg }
// take queues m on its key's worker, starting the worker when none runs.
func (w *eventWorkers) take(m jetstream.Msg) {
key := w.keyOf(m)
w.mu.Lock()
if w.queues == nil {
w.queues = map[string]*eventQueue{}
}
q, running := w.queues[key]
if !running {
q = &eventQueue{}
w.queues[key] = q
}
q.msgs = append(q.msgs, m)
w.mu.Unlock()
if !running {
go w.run(key, q)
}
}
// run handles key's events in order until its queue is empty, saying those still waiting in progress after each.
func (w *eventWorkers) run(key string, q *eventQueue) {
for {
w.mu.Lock()
if len(q.msgs) == 0 {
delete(w.queues, key)
w.mu.Unlock()
return
}
m := q.msgs[0]
w.mu.Unlock()
w.handle(m)
w.mu.Lock()
q.msgs = q.msgs[1:]
waiting := slices.Clone(q.msgs)
w.mu.Unlock()
for _, m := range waiting {
_ = m.InProgress()
}
}
}
// eventKey is the worker key of a builder's event (H-A-514 second addendum): a registry seat's outcome's name, a
// version-released's module, else "" (one worker for the events naming none).
func eventKey(m jetstream.Msg) string {
if _, ok := seatEvents[m.Subject()]; ok {
var o versions.Outcome
if json.Unmarshal(m.Data(), &o) == nil {
return "name " + o.Name
}
return ""
}
if m.Subject() == meshcatalog.SubjectVersionReleased {
var ev meshcatalog.VersionReleasedEvent
if json.Unmarshal(m.Data(), &ev) == nil {
return "module " + ev.Module
}
}
return ""
}
@@ -1,87 +0,0 @@
package main
import (
"context"
"errors"
"sync/atomic"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
)
// lastKept reads whether the stream keeps a message on a subject: found false when the stream or the message is not there.
type lastKept func(ctx context.Context, subject string) (found bool, err error)
// lastKeptOf reads the seat event's own kept stream (the contract's StreamVersionsFilled, kept by age) the way any kept event
// is heard (design 47 G A-411, A-233): the SDK's hearing of it from its first message, whose start read hands every message
// kept to the handler; the reading is stopped once the read ended, the hub's own hearing following the durable. Nothing of
// EVENTS is read.
func lastKeptOf(js jetstream.JetStream, acct process.Account, logf func(string, ...any)) lastKept {
return func(ctx context.Context, subject string) (bool, error) {
var found atomic.Bool
cc, err := acct.HearSeatEvents(ctx, js, meshcatalog.StreamVersionsFilled, func(m jetstream.Msg) {
if m.Subject() == subject {
found.Store(true)
}
_ = m.Ack() // a message of the durable is taken as the hub takes it; an ordered read's has nothing to acknowledge
}, logf, process.FromFirst())
if err != nil {
if errors.Is(err, jetstream.ErrStreamNotFound) {
return false, nil
}
return false, err
}
cc.Stop()
return found.Load(), nil
}
}
// readFilled reads at the builder's start the last versions-filled the stream keeps (design 47 G §369, §372, A-411) and takes it as heard; the event heard later sets it as before. Nothing found leaves it unset, said; a
// read that failed is said and tried again in the background with backoff, never holding the start.
func (rv *reservations) readFilled(ctx context.Context, read lastKept, wait func(context.Context, time.Duration) bool) {
const first, most = time.Second, time.Minute
try := func() (done bool, err error) {
found, err := read(ctx, meshcatalog.SubjectVersionsFilled)
if err != nil {
return false, err
}
if !found {
rv.logf("the stream keeps no versions-filled yet (read at start): versions are reserved once the catalog says it")
return true, nil
}
rv.filled.Store(true)
rv.logf("the catalog said versions-filled (read at start): versions are reserved from now on")
if rv.wake != nil {
rv.wake(ctx)
}
return true, nil
}
if done, err := try(); done {
return
} else {
rv.logf("the last versions-filled is not read at start: %v; read again in the background", err)
}
go func() {
for d := first; ; d = min(d*2, most) {
if !wait(ctx, d) {
return
}
done, err := try()
if done {
return
}
rv.logf("the last versions-filled is not read: %v; read again in %s", err, min(d*2, most))
}
}()
}
// sleeps waits d, as a context's bound (ADR 0437 §8: the builder holds no timer); false when ctx ended first.
func sleeps(ctx context.Context, d time.Duration) bool {
bound, cancel := context.WithTimeout(ctx, d)
defer cancel()
<-bound.Done()
return ctx.Err() == nil
}
@@ -1,64 +0,0 @@
package main
import (
"context"
"errors"
"reflect"
"sync"
"testing"
"time"
)
func TestTheLastVersionsFilledIsReadAtStart(t *testing.T) {
boom := errors.New("bus down")
for _, tc := range []struct {
name string
results []error // per read: nil found, boom fails
notFound bool
wantFilled bool
wantReads int
waits []time.Duration
}{
{"kept", []error{nil}, false, true, 1, nil},
{"none kept", []error{nil}, true, false, 1, nil},
{"read fails then kept", []error{boom, boom, nil}, false, true, 3, []time.Duration{time.Second, 2 * time.Second}},
} {
t.Run(tc.name, func(t *testing.T) {
rv := newReservations(nil, nil, nil, nil, nil, t.Logf)
var mu sync.Mutex
woke := make(chan struct{}, 1)
rv.wake = func(context.Context) { woke <- struct{}{} }
reads := 0
read := func(_ context.Context, subject string) (bool, error) {
mu.Lock()
defer mu.Unlock()
err := tc.results[reads]
reads++
return !tc.notFound, err
}
var waits []time.Duration
wait := func(_ context.Context, d time.Duration) bool {
mu.Lock()
defer mu.Unlock()
waits = append(waits, d)
return true
}
rv.readFilled(context.Background(), read, wait)
if tc.wantFilled {
select {
case <-woke:
case <-time.After(5 * time.Second):
t.Fatal("the read did not take the fill")
}
}
mu.Lock()
defer mu.Unlock()
if rv.Filled() != tc.wantFilled || reads != tc.wantReads {
t.Fatalf("filled %v reads %d", rv.Filled(), reads)
}
if !reflect.DeepEqual(waits, tc.waits) {
t.Fatalf("backoff %v, want %v", waits, tc.waits)
}
})
}
}
@@ -13,18 +13,17 @@ import (
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-sdk/go/views" "git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-builder/internal/versions"
) )
// heldWriter is the builder's finding writer: its findings are raised as they happen, so the writer holds them (design 47 G // heldWriter is the builder's finding writer: its findings are raised as they happen, so the writer holds them (design 47 G
// A-29); its `findings-asked` subject is the seat's, from the generated contract (A-17). // A-29); its `findings-asked` subject is the seat's, from the generated contract (A-17).
type heldWriter = views.HeldWriter[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent] type heldWriter = views.HeldWriter[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent]
// findingWriter is the part of the held writer the builder's findings use. // findingWriter is the part of the held writer the builder's findings use; Held answers the findings it holds (design 47 G A-38).
type findingWriter interface { type findingWriter interface {
Write(ctx context.Context, f mcseat.Finding) error Write(ctx context.Context, f mcseat.Finding) error
Clear(ctx context.Context, scope, id, kind, why string) error Clear(ctx context.Context, scope, id, kind, why string) error
Held() []mcseat.Finding
} }
// findings writes the builder's findings through its held finding writer (design 47 G §689, A-29): a finding written before the // findings writes the builder's findings through its held finding writer (design 47 G §689, A-29): a finding written before the
@@ -115,6 +114,19 @@ func (f *findings) raise(ctx context.Context, fd finding) {
} }
} }
// stands says whether the writer holds the finding of kind about scope and id (design 47 G A-38): it is raised and not cleared.
func (f *findings) stands(kind, scope, id string) bool {
if f.w == nil {
return false
}
for _, x := range f.w.Held() {
if x.Kind == kind && x.Scope == scope && x.ID == keyID(id) {
return true
}
}
return false
}
// clear clears the finding of kind about scope and id; one not there is nothing to clear. // clear clears the finding of kind about scope and id; one not there is nothing to clear.
func (f *findings) clear(ctx context.Context, kind, scope, id string) { func (f *findings) clear(ctx context.Context, kind, scope, id string) {
if f.w == nil { if f.w == nil {
@@ -151,19 +163,3 @@ func (f *findings) notHeard(ctx context.Context) heard.Writer {
return f.w.Clear(ctx, scope, rest[:i], rest[i+1:], "the builder hears it") return f.w.Clear(ctx, scope, rest[:i], rest[i+1:], "the builder hears it")
}} }}
} }
// floorSaid is the floor finding (design 51 *Health and conditions*: a floor source silent): raised for a name waiting on
// its floor, about that name, cleared once all three sources answered.
func (f *findings) floorSaid(ctx context.Context) func(versions.FloorWait, bool) {
return func(w versions.FloorWait, raised bool) {
if !raised {
f.clear(ctx, versions.FloorSilent, mcc.ScopeModule, w.Name)
return
}
f.raise(ctx, finding{kind: versions.FloorSilent, scope: mcc.ScopeModule, id: w.Name, summary: w.Finding(),
headline: "A version's floor is not known",
explanation: "The builder numbers a name only once its registry seat, the forge bridge's tags and the indexer's requirements all answered; one of them did not.",
resolved: "All three answered.",
needs: "builder_floor_waits names the silent source; builder_floor_again asks again by hand."})
}
}
@@ -14,8 +14,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
sweep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshartifactsweep" sweep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshartifactsweep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
) )
// A done key whose blob the artifact store no longer holds is built again, by the builder whole against the bus // A done key whose blob the artifact store no longer holds is built again, by the builder whole against the bus
@@ -194,31 +192,3 @@ func artifactsGoneLeadsTheBuilderToBuildTheKeyAgain(t *testing.T) {
b.fake.count("mesh-build-go.build_go_build")) b.fake.count("mesh-build-go.build_go_build"))
} }
} }
// The last versions-filled is read at the start from the seat event's own kept stream, kept by age, through the SDK's hearing
// from the first message (design 47 G A-411), never from EVENTS: a message the stream keeps is found, an empty one is none.
func TestTheLastVersionsFilledIsReadFromItsKeptStream(t *testing.T) {
b := startBed(t)
acct := process.Account{Node: "n1", Module: "mesh-delivery-builder"}
if err := b.js.DeleteStream(b.ctx, eventsStream); err != nil { // the bus keeps a kept event off EVENTS: its subject is nowhere else
t.Fatal(err)
}
if _, err := b.js.CreateOrUpdateStream(b.ctx, jetstream.StreamConfig{Name: meshcatalog.StreamVersionsFilled,
Subjects: []string{meshcatalog.SubjectVersionsFilled}, MaxAge: 24 * time.Hour}); err != nil {
t.Fatal(err)
}
if _, err := b.js.CreateOrUpdateConsumer(b.ctx, meshcatalog.StreamVersionsFilled, jetstream.ConsumerConfig{
Durable: acct.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy, FilterSubject: meshcatalog.SubjectVersionsFilled}); err != nil {
t.Fatal(err)
}
read := lastKeptOf(b.js, acct, t.Logf)
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || found {
t.Fatalf("empty stream: found %v, %v", found, err)
}
if _, err := b.js.Publish(b.ctx, meshcatalog.SubjectVersionsFilled, []byte(`{"v":1}`)); err != nil {
t.Fatal(err)
}
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || !found {
t.Fatalf("kept message: found %v, %v", found, err)
}
}
@@ -9,10 +9,8 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"maps"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
@@ -31,6 +29,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry"
@@ -40,6 +39,7 @@ import (
"git.novox.be/novox/mesh-sdk/go/buscompose" "git.novox.be/novox/mesh-sdk/go/buscompose"
"git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/seatdef" "git.novox.be/novox/mesh-sdk/go/seatdef"
"git.novox.be/novox/mesh-sdk/go/testbus"
"git.novox.be/novox/mesh-sdk/go/views/viewstest" "git.novox.be/novox/mesh-sdk/go/views/viewstest"
"mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/build"
@@ -176,6 +176,8 @@ func (f *fakeBuildModules) step(module, name string, args map[string]any) (any,
return json.RawMessage(`{"artifact":"` + fmt.Sprint(args["artifact"]) + `","digest":"` + d + `","reference":"registry.example/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@` + d + `","pushed":true}`), nil return json.RawMessage(`{"artifact":"` + fmt.Sprint(args["artifact"]) + `","digest":"` + d + `","reference":"registry.example/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@` + d + `","pushed":true}`), nil
case tool != "build_image_build" && f.refusePush.Load(): case tool != "build_image_build" && f.refusePush.Load():
return nil, fmt.Errorf("%s%v: the artifact store answered 507 Insufficient Storage", builds.NotStored, args["artifact"]) return nil, fmt.Errorf("%s%v: the artifact store answered 507 Insufficient Storage", builds.NotStored, args["artifact"])
case tool == "build_go_build" && args["seat"] == "go-package-registry": // a Go package under a reserved version: <name>@<version>
return json.RawMessage(`{"digest":"` + digestOf(fmt.Sprint(args["artifact"])) + `","reference":"git.novox.be/novox/mesh-catalog/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@v` + fmt.Sprint(args["version"]) + `"}`), nil
case tool != "build_image_build": // a bundle or an archive is pushed and its reference answered (ADR 0498 clause 1) case tool != "build_image_build": // a bundle or an archive is pushed and its reference answered (ADR 0498 clause 1)
d := digestOf(fmt.Sprint(args["artifact"])) d := digestOf(fmt.Sprint(args["artifact"]))
return json.RawMessage(`{"digest":"` + d + `","reference":"artifact-store://` + filepath.Base(fmt.Sprint(args["module"])) + `/` + fmt.Sprint(args["artifact"]) + `/blobs/` + d + `"}`), nil return json.RawMessage(`{"digest":"` + d + `","reference":"artifact-store://` + filepath.Base(fmt.Sprint(args["module"])) + `/` + fmt.Sprint(args["artifact"]) + `/blobs/` + d + `"}`), nil
@@ -322,7 +324,7 @@ func startBedWith(t *testing.T, closed bool) *bed {
// each have their durable consumer. // each have their durable consumer.
b.catalog = newCatalogHolder(t, ctx, js, ctl) b.catalog = newCatalogHolder(t, ctx, js, ctl)
b.catalog.buildSeats(t, ctl, map[string]string{"node-build-go": testGo, "node-build-node": testNode, "node-build-image": testImage, b.catalog.buildSeats(t, ctl, map[string]string{"node-build-go": testGo, "node-build-node": testNode, "node-build-image": testImage,
"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer", // the floor's sources are the holders of git and mesh-catalog "git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer",
"mesh-builds": builds.BuilderModule}) // the builder's own seat, whose verb reserved it answers once its definition is read (A-115, A-278) "mesh-builds": builds.BuilderModule}) // the builder's own seat, whose verb reserved it answers once its definition is read (A-115, A-278)
readers := []string{"n1_" + builds.BuilderModule, "n2_" + builds.BuilderModule} readers := []string{"n1_" + builds.BuilderModule, "n2_" + builds.BuilderModule}
// Design 47 G §717, A-298: the catalog half names testAssigner the claimant of mesh-module-assigner, and its seat-holders view // Design 47 G §717, A-298: the catalog half names testAssigner the claimant of mesh-module-assigner, and its seat-holders view
@@ -570,7 +572,7 @@ func isState(state string) func(builds.BuilderBuild) bool {
// the digests of both bundles, both build modules' toolchains, after a fetch and a build on one node (ADR 0478 clause 4). // the digests of both bundles, both build modules' toolchains, after a fetch and a build on one node (ADR 0478 clause 4).
func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7 func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
b := startBed(t) b := startBed(t)
// The builder's versions, findings and the floor's three sources are on the bus, the seat answering 0.1.4; two merges close // The builder's findings are on the bus, the seat answering 0.1.4; two merges close
// together, the first replaced before its claim. The builder numbers neither in its state versions (design 47 H H-A-159, // together, the first replaced before its claim. The builder numbers neither in its state versions (design 47 H H-A-159,
// G §348, §369): the reservation is the one place a version is numbered. // G §348, §369): the reservation is the one place a version is numbered.
reg := b.registry(t, "n1", "0.1.4") reg := b.registry(t, "n1", "0.1.4")
@@ -578,14 +580,11 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
first := "src2:" + strings.Repeat("1", 64) first := "src2:" + strings.Repeat("1", 64)
b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, commit, first, 1) b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, commit, first, 1)
digest := b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, commit, fp, 2) digest := b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, commit, fp, 2)
b.start(t, "n1", map[string]string{"MESH_BUILDER_STEP_BOUND": "1s"}) // H-A-473 (addendum): the builds that must end done run under the level bound's set-up share, never a bound a loaded
// node cannot meet; the hung step's part below starts the builder again at a short bound of its own.
doneBound := map[string]string{"MESH_BUILDER_STEP_BOUND": testbus.SetupBound(t).String()}
b.start(t, "n1", doneBound)
v := b.await(t, "netcheck", isState(builds.BuildDone)) v := b.await(t, "netcheck", isState(builds.BuildDone))
for _, a := range []string{"tools-go", "tools-typescript"} {
es := reg.of(t, "netcheck/"+a)
if len(es) != 0 {
t.Errorf("versions of netcheck/%s = %+v, want none: the builder numbers nothing of its own (H-A-159)", a, es)
}
}
if v.By != "n1.mesh-delivery-builder" || v.Manifest != digest || len(v.Artifacts) != 2 { if v.By != "n1.mesh-delivery-builder" || v.Manifest != digest || len(v.Artifacts) != 2 {
t.Fatalf("build = %+v", v) t.Fatalf("build = %+v", v)
} }
@@ -618,7 +617,7 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
for _, e := range b.logged(t, "netcheck") { for _, e := range b.logged(t, "netcheck") {
if e.Event != builds.BuildSaidEvent { if e.Event != builds.BuildSaidEvent {
ended = append(ended, e) ended = append(ended, e)
} else if e.Why == versions.SaidNumbered || e.Why == versions.SaidKept { } else if e.Why == "numbered" || e.Why == "kept" { // the narrations of the numbering from before G (design 47 H §756)
t.Errorf("said = %+v, want no version of the builder's own numbered (H-A-159)", e) t.Errorf("said = %+v, want no version of the builder's own numbered (H-A-159)", e)
} }
} }
@@ -654,45 +653,13 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 { if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got) t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
} }
// Versions numbered before G, which the state keeps until G §372 removes it: one a holder removes below, one it refuses.
kept, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-typescript", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.5", Module: "netcheck",
Fingerprint: fp, Digest: digestOf("tools-typescript"), Seat: ociartifactregistry.Seat, State: versions.Published, At: time.Now().UTC()})
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-typescript", "0.1.5"), kept); err != nil {
t.Fatal(err)
}
refusable, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-go", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.6", Module: "netcheck",
Fingerprint: "src2:" + strings.Repeat("6", 64), Seat: ociartifactregistry.Seat, State: versions.Numbered, At: time.Now().UTC()})
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-go", "0.1.6"), refusable); err != nil {
t.Fatal(err)
}
// Running-testing note (review round 1): two claims never get one number on the bus's own compare-and-set, as
// the builder's state versions keeps them: eight claims of one name at once, eight versions.
store := versions.Versions{Store: awaitedVersions{b: process.AwaitBucket(b.ctx, b.js, nil, builds.StateBucket(builds.BuilderModule, versions.State), "", t.Logf)}}
numbers := make(chan string, 8)
var claims sync.WaitGroup
for i := range 8 {
claims.Go(func() {
d, _, err := store.Number(b.ctx, versions.Claim{Name: "netcheck/race", Kind: versions.KindBundle, Fingerprint: fmt.Sprintf("f%d", i)})
if err != nil {
t.Error(err)
}
numbers <- d.Version
})
}
claims.Wait()
close(numbers)
got := map[string]bool{}
for v := range numbers {
got[v] = true
}
if len(got) != 8 {
t.Errorf("eight claims of one name at once were numbered %v, want eight versions", slices.Sorted(maps.Keys(got)))
}
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 { if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got) t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
} }
// DLV-B10: a build module's bound running out fails the trunk build, which is the builder's finding build-failed; the // DLV-B10: a build module's bound running out fails the trunk build, which is the builder's finding build-failed; the
// fingerprint built again clears it with its done build, numbering nothing of the builder's own (H-A-159). // fingerprint built again clears it with its done build, numbering nothing of the builder's own (H-A-159).
b.stop()
b.start(t, "n1", map[string]string{"MESH_BUILDER_STEP_BOUND": "1s"}) // a step that never ends runs out of any bound
release := make(chan struct{}) release := make(chan struct{})
b.fake.hang.Store(&release) b.fake.hang.Store(&release)
third := "src2:" + strings.Repeat("4", 64) third := "src2:" + strings.Repeat("4", 64)
@@ -713,23 +680,119 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
reg.awaitFinding(t, failed, true) reg.awaitFinding(t, failed, true)
b.fake.hang.Store(nil) b.fake.hang.Store(nil)
close(release) close(release)
b.stop() // the build again must end done
b.start(t, "n1", doneBound)
b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, "89abcdef0123456789abcdef0123456789abcdef", third, 3) // the entry moves to a later commit, same fingerprint b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, "89abcdef0123456789abcdef0123456789abcdef", third, 3) // the entry moves to a later commit, same fingerprint
b.awaitFP(t, "netcheck", third, isState(builds.BuildDone)) b.awaitFP(t, "netcheck", third, isState(builds.BuildDone))
reg.awaitFinding(t, failed, false) reg.awaitFinding(t, failed, false)
// DLV-B4: the seats' refused and removed, heard on the builder's durable consumer, move a numbered version: a retention // DLV-B4: a seat's refused, heard on the builder's durable consumer, is the finding publish-refused about the name with the
// removal turns the entry removed with its reason, a refusal refused with the holder's reason and the bytes it refused. // holder's reason; the numbering from before G, which marked its state versions, is gone (design 47 H §756).
reg.outcome(t, ociartifactregistry.SubjectRemoved, versions.Outcome{Name: "netcheck/tools-typescript", Version: "0.1.5", Kind: "bundle", Holder: "distribution", Reason: "retention"})
reg.outcome(t, ociartifactregistry.SubjectRefused, versions.Outcome{Name: "netcheck/tools-go", Version: "0.1.6", Digest: digestOf("other"), Kind: "bundle", Holder: "distribution", Reason: "the cap"}) reg.outcome(t, ociartifactregistry.SubjectRefused, versions.Outcome{Name: "netcheck/tools-go", Version: "0.1.6", Digest: digestOf("other"), Kind: "bundle", Holder: "distribution", Reason: "the cap"})
reg.awaitOf(t, "netcheck/tools-typescript", func(es []versions.Entry) bool { reg.awaitFinding(t, meshconditionsclient.Key(meshconditionsclient.ScopeModule, "netcheck/tools-go", versions.PublishRefused), true)
return slices.ContainsFunc(es, func(e versions.Entry) bool { // Issue 721 B4 (design 47 H2 H-A-521, H-A-547 (3), H-A-551): an entry naming a mesh package with no version is built with
return e.Version == "0.1.5" && e.State == versions.Removed && e.Reason == "retention" // the version its publisher reserved at the source revision of the key's own origin, once that reservation's artifact is
}) // published, never the newest version a registry seat said published; once the version is released and the reservation
}) // gone, the next such build takes it from the release record.
reg.awaitOf(t, "netcheck/tools-go", func(es []versions.Entry) bool { const pkg = "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings"
return slices.ContainsFunc(es, func(e versions.Entry) bool { goPublished := func(version, digest string) {
return e.Version == "0.1.6" && e.State == versions.Refused && e.Reason == "the cap" && e.RefusedDigest == digestOf("other") t.Helper()
}) reg.outcome(t, gopackageregistry.SubjectPublished, versions.Outcome{Name: pkg, Version: version, Digest: digest, Kind: versions.KindPackage, Holder: "go-registry"})
}) }
// The reservations' states, as the controller makes them from the builder's manifest, and the catalog seat's versions, which
// a first reservation reads (none released yet).
for _, state := range []string{versions.ReservedState, versions.ActedState} { // acted keeps the release record
if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, state)}); err != nil {
t.Fatal(err)
}
}
none, _ := json.Marshal(map[string]any{"result": meshcatalog.VersionsAnswer{Module: "disk-load", Versions: []meshcatalog.VersionEntry{}}, "node": "ctl"})
if s, err := b.js.Conn().Subscribe("mesh.seat."+meshcatalog.Seat+".call.versions.>", func(m *nats.Msg) { _ = m.Respond(none) }); err != nil {
t.Fatal(err)
} else {
defer s.Unsubscribe()
}
goPublished("9.9.9", digestOf("elsewhere")) // the newest a registry seat said published: of no reservation at this origin
b.awaitSaid(t, "the published of "+pkg+"@9.9.9")
const diskLoad = "catalogue-8b8b0f66-disk-load.module.json"
raw, err := os.ReadFile(filepath.Join("testdata", diskLoad))
if err != nil {
t.Fatal(err)
}
pubFP := "src2:" + strings.Repeat("5", 64)
publisher := b.entry("disk-load", "modules/disk-load", commit, pubFP, meshcatalogclient.ManifestDigest(raw), b.manifestOf(t, diskLoad), bothToolchains, 0)
publisher.Artifacts = []meshcatalog.Artifact{{Ref: "disk-load:diskreadings", Kind: versions.KindPackage, Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: pkg}}}
b.catalog.put(t, publisher)
importer := func(fp2 string) {
t.Helper()
e := b.entry("netcheck", "modules/netcheck", commit, fp2, digest, b.manifestOf(t, netcheck), bothToolchains, 0)
e.Packages = map[string]string{pkg: ""}
b.catalog.put(t, e)
}
fourth := "src2:" + strings.Repeat("6", 64)
importer(fourth)
pub := b.awaitFP(t, "disk-load", pubFP, isState(builds.BuildDone))
conn, err := process.Connect(process.Account{URL: b.srvURL, Module: "mesh-delivery-view", User: "ctl", Password: "pw"})
if err != nil {
t.Fatal(err)
}
defer conn.Close()
answer, err := conn.Call("seat:mesh-builds.reserved", meshbuilds.ReservedInput{Module: "disk-load"})
var reserved meshbuilds.ReservedAnswer
if err != nil || json.Unmarshal(answer, &reserved) != nil || reserved.Version == "" {
t.Fatalf("reserved of disk-load = %s, %v; want the version its trunk build reserved", answer, err)
}
pkgDigest := ""
for _, a := range pub.Artifacts {
if a.Name == "diskreadings" {
pkgDigest = a.Digest
}
}
b.awaitSaid(t, "package "+pkg+" has no published version")
goPublished(reserved.Version, pkgDigest)
want := "v" + reserved.Version
if v := b.awaitFP(t, "netcheck", fourth, isState(builds.BuildDone)); v.Packages[pkg] != want {
t.Errorf("netcheck built with %v, want %s at %s, its publisher's reservation at the key's origin (H-A-547 (3))", v.Packages, pkg, want)
}
released, _ := json.Marshal(meshcatalog.VersionReleasedEvent{V: 1, Module: "disk-load", Version: reserved.Version})
msg := nats.NewMsg(meshcatalog.SubjectVersionReleased)
msg.Header.Set("x-event-id", "released-disk-load-"+reserved.Version)
msg.Data = released
if _, err := b.js.PublishMsg(b.ctx, msg); err != nil {
t.Fatal(err)
}
// The release deletes the reservation (H-A-551): what fills the next build is the release record alone.
reservations, err := b.js.KeyValue(b.ctx, builds.StateBucket(builds.BuilderModule, versions.ReservedState))
if err != nil {
t.Fatal(err)
}
// Watched, never polled: the watch gives the keys standing, then a nil, then each change (the delete of the release).
w, err := reservations.WatchFiltered(b.ctx, []string{versions.NameFilter("disk-load")})
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Stop() }()
held, caughtUp := map[string]bool{}, false
timeout := time.After(20 * time.Second)
for !caughtUp || len(held) > 0 {
select {
case e := <-w.Updates():
switch {
case e == nil:
caughtUp = true
case e.Operation() == jetstream.KeyValuePut:
held[e.Key()] = true
default:
delete(held, e.Key())
}
case <-timeout:
t.Fatalf("disk-load holds %v 20 s after its version-released of %s, want none", held, reserved.Version)
}
}
fifth := "src2:" + strings.Repeat("7", 64)
importer(fifth)
if v := b.awaitFP(t, "netcheck", fifth, isState(builds.BuildDone)); v.Packages[pkg] != want {
t.Errorf("netcheck built with %v once disk-load %s was released, want %s at %s from its release record (H-A-551)", v.Packages, reserved.Version, pkg, want)
}
} }
// TestAnArchiveOnlyModuleAndARootModuleAreBuilt: the indexer gives an archive no language, so modules.ca-trust has no // TestAnArchiveOnlyModuleAndARootModuleAreBuilt: the indexer gives an archive no language, so modules.ca-trust has no
@@ -1146,15 +1209,14 @@ func TestARestartedBuilderPutsNoSecondAsk(t *testing.T) {
} }
} }
// registry is the part of the bed design 51's builder cases need: the builder's states versions, findings, floor-waits and // registry is the part of the bed design 51's builder cases need: the builder's states findings and reasks, EVENTS
// reasks, EVENTS with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's // with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's own events kept, and
// own events kept, and the floor's three sources served on the bus as their holders answer through the tool runner // the seat's versions served on the bus as its holder answers through the tool runner ({result}).
// ({result}): the seat's versions, the seat git's tags and the indexer's indexer_requirements.
type registry struct { type registry struct {
b *bed b *bed
versions, findings, reasks jetstream.KeyValue findings, reasks jetstream.KeyValue
mu sync.Mutex mu sync.Mutex
numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349 numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349
} }
func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *registry { func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *registry {
@@ -1167,8 +1229,7 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
} }
return kv return kv
} }
r.versions, r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, versions.State)), mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState)) r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState))
mk(builds.StateBucket(builds.BuilderModule, versions.FloorWaitsState))
// EVENTS with two seats' outcomes, and the forge bridge's stream (a branch's end): each with the builder's durable consumer. // EVENTS with two seats' outcomes, and the forge bridge's stream (a branch's end): each with the builder's durable consumer.
for stream, subjects := range map[string][]string{ for stream, subjects := range map[string][]string{
eventsStream: {"mesh.mod.*.event.>", "mesh.seat.*.event.>"}, eventsStream: {"mesh.mod.*.event.>", "mesh.seat.*.event.>"},
@@ -1198,7 +1259,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
} }
for subject, answer := range map[string]any{ for subject, answer := range map[string]any{
"mesh.seat." + ociartifactregistry.Seat + ".call.versions.>": map[string]any{"versions": listed}, "mesh.seat." + ociartifactregistry.Seat + ".call.versions.>": map[string]any{"versions": listed},
"mesh.seat.git.call.tags.>": map[string]any{"tags": []string{}},
} { } {
reply, _ := json.Marshal(map[string]any{"result": answer, "node": "ctl"}) reply, _ := json.Marshal(map[string]any{"result": answer, "node": "ctl"})
s, err := nc.Subscribe(subject, func(m *nats.Msg) { _ = m.Respond(reply) }) s, err := nc.Subscribe(subject, func(m *nats.Msg) { _ = m.Respond(reply) })
@@ -1210,42 +1270,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
return r return r
} }
// of is every entry versions holds of name.
func (r *registry) of(t *testing.T, name string) []versions.Entry {
t.Helper()
l, err := r.versions.ListKeysFiltered(r.b.ctx, versions.NameFilter(name))
if err != nil {
t.Fatal(err)
}
defer func() { _ = l.Stop() }()
var out []versions.Entry
for k := range l.Keys() {
e, err := r.versions.Get(r.b.ctx, k)
if err != nil {
t.Fatal(err)
}
var v versions.Entry
if err := json.Unmarshal(e.Value(), &v); err != nil {
t.Fatal(err)
}
out = append(out, v)
}
return out
}
// awaitOf reads name's entries until pred holds of them, within 20 s.
func (r *registry) awaitOf(t *testing.T, name string, pred func([]versions.Entry) bool) []versions.Entry {
t.Helper()
var es []versions.Entry
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
if es = r.of(t, name); pred(es) {
return es
}
}
t.Fatalf("versions of %s = %+v within 20 s", name, es)
return es
}
// published says the artifact seat's published for name@version, as its holder does. // published says the artifact seat's published for name@version, as its holder does.
func (r *registry) published(t *testing.T, name, version, digest string) { func (r *registry) published(t *testing.T, name, version, digest string) {
t.Helper() t.Helper()
@@ -159,26 +159,12 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
conn.SetReconnectHandler(func(*nats.Conn) { hearing.Again(); heard.Nudge("") }) conn.SetReconnectHandler(func(*nats.Conn) { hearing.Again(); heard.Nudge("") })
// The builder asks the controller, as its own account, whether the artifact store still holds a done key's blobs // The builder asks the controller, as its own account, whether the artifact store still holds a done key's blobs
// (the seat verb held, novox/hq issue 1937) before it leaves the key done, on its calls connection. // (the seat verb held, novox/hq issue 1937) before it leaves the key done, on its calls connection.
// The state versions, kept from before G (design 51 *The versions*) and read through builder_versions until G §372 removes
// it, bound once the bus holds it; the builder numbers nothing in it (design 47 H H-A-159).
versionsKV := process.AwaitBucket(ctx, js, conn, own.versions, "builder_versions answers nothing of the versions numbered before G", logger.Printf)
found := &findings{module: cred.Module, w: fw, logf: logger.Printf, now: time.Now} found := &findings{module: cred.Module, w: fw, logf: logger.Printf, now: time.Now}
floorWaits := &versions.FloorWaits{Holder: versions.HolderOf(branches), Logf: logger.Printf, Said: found.floorSaid(context.WithoutCancel(ctx))}
// The names waiting on their floor are kept in the state floor-waits (DLV-B4): a restarted builder takes them in, so
// their silent sources' events still wake them; until the state is bound they are kept here only.
process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, versions.FloorWaitsState), "the names waiting on their floor are kept in memory only, and builder_floor_waits shows none", logger.Printf).
Ready(func(kv jetstream.KeyValue) {
floorWaits.Keep(kvKeeper{ctx: ctx, kv: kv}, heldFloorWaits(ctx, kv, logger.Printf))
})
// A package is numbered under its name in its ecosystem, read from the catalog half's entries (design 32, design 47 G §348).
numberer := &versions.Numberer{Versions: versions.Versions{Store: awaitedVersions{b: versionsKV}}, Floor: floorVia(calls.Call, versions.RequirementsFrom(versions.EntriesOf(branches))), Waits: floorWaits,
Names: versions.NamesFrom(versions.EntriesOf(branches))}
// A publish that ends badly is a finding (design 51 *Health and conditions*): a holder's refused, a version no holder // A publish that ends badly is a finding (design 51 *Health and conditions*): a holder's refused, a version no holder
// answered within its bound (a key of the state bounds with its own time to live), a seat's outcome that does not read. // answered within its bound (a key of the state bounds with its own time to live), a seat's outcome that does not read.
pubBoundsKV := process.AwaitBucket(ctx, js, conn, own.bounds, "a publish no holder answers, and a node holding the old form seven days, are not raised", logger.Printf) pubBoundsKV := process.AwaitBucket(ctx, js, conn, own.bounds, "a publish no holder answers, and a node holding the old form seven days, are not raised", logger.Printf)
stepReads.bounds, stepReads.findings = func() jetstream.KeyValue { return pubBoundsKV.KV() }, found stepReads.bounds, stepReads.findings = func() jetstream.KeyValue { return pubBoundsKV.KV() }, found
pubs := &publishes{bounds: pubBoundsKV.KV, versions: numberer.Versions, findings: found, bound: versions.PublishBound, logf: logger.Printf} pubs := &publishes{findings: found}
numberer.Publishing = pubs.arm
stepExpiry := &buildrun.Expiry{} stepExpiry := &buildrun.Expiry{}
var b *build.Builder var b *build.Builder
seatsChanged := func(ctx context.Context) { seatsChanged := func(ctx context.Context) {
@@ -211,9 +197,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
unput := &unputs{bounds: pubBoundsKV.KV, store: b.Claimer.Store, looking: b.Looking, findings: found, unput := &unputs{bounds: pubBoundsKV.KV, store: b.Claimer.Store, looking: b.Looking, findings: found,
bound: meshconditionsclient.CallUnansweredAfter, now: time.Now, logf: logger.Printf} bound: meshconditionsclient.CallUnansweredAfter, now: time.Now, logf: logger.Printf}
b.Left, b.Ended = unput.left, unput.ended b.Left, b.Ended = unput.left, unput.ended
// The builder numbers nothing of its own (design 47 H H-A-159, G §348, §349, §369): b.Numbers stays nil, so no trunk build // The builder numbers nothing of its own and asks no floor (design 47 H §756, H H-A-159, G §348, §349, §369): the
// is numbered in the state versions, waits on a floor or arms a publish-unanswered bound of it; the reservation is the one // reservation is the one place a version is numbered.
// place a version is numbered. The state, kept from before G, is still read (builder_versions) until G §372 removes it.
// The builder's toolchain waits (design 47 G §672): its state waits, and wait-held and wait-ended on its stream waits; its // The builder's toolchain waits (design 47 G §672): its state waits, and wait-held and wait-ended on its stream waits; its
// bound is its setting toolchain-wait-minutes. // bound is its setting toolchain-wait-minutes.
waitBound, err := toolchainWaitOf(getenv("MESH_BUILDER_TOOLCHAIN_WAIT_FILE")) waitBound, err := toolchainWaitOf(getenv("MESH_BUILDER_TOOLCHAIN_WAIT_FILE"))
@@ -233,8 +218,12 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return err return err
} }
b.PackageWait = time.Duration(packageWait) * time.Minute b.PackageWait = time.Duration(packageWait) * time.Minute
// Before it waits for an unpinned package, the build reads what the Go package registry seat holds of it (H-A-194). // A version's digests are recorded under the builder's own bound, never the build's (H-A-492); it is record-bound-seconds.
b.PublishedVersions = publishedVersionsVia(calls.Call) recordBound, err := numberFile(getenv("MESH_BUILDER_RECORD_BOUND_FILE"), int(build.DefaultRecordBound/time.Second))
if err != nil {
return err
}
b.RecordBound = time.Duration(recordBound) * time.Second
waitsBucket := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.WaitsState), "the toolchain waits are kept in memory only, and builder_waits shows none", logger.Printf) waitsBucket := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.WaitsState), "the toolchain waits are kept in memory only, and builder_waits shows none", logger.Printf)
b.Waits = newWaitsKept(waitsBucket, func(ctx context.Context, event, id string, body any) error { b.Waits = newWaitsKept(waitsBucket, func(ctx context.Context, event, id string, body any) error {
return emitEvent(context.WithoutCancel(ctx), js, cred, event, id, body) return emitEvent(context.WithoutCancel(ctx), js, cred, event, id, body)
@@ -242,10 +231,10 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
waitsBucket.Ready(func(kv jetstream.KeyValue) { b.Waits.(*waitsKept).start(ctx, kv) }) waitsBucket.Ready(func(kv jetstream.KeyValue) { b.Waits.(*waitsKept).start(ctx, kv) })
// The plans no seat builds (design 47 H2 §795, H-A-425): kept in the state unbuildable, read by builder_unbuildable. // The plans no seat builds (design 47 H2 §795, H-A-425): kept in the state unbuildable, read by builder_unbuildable.
b.Unbuildables = unbuildableKept{b: process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.UnbuildableState), "the plans no seat builds are said, and builder_unbuildable lists none", logger.Printf)} b.Unbuildables = unbuildableKept{b: process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.UnbuildableState), "the plans no seat builds are said, and builder_unbuildable lists none", logger.Printf)}
// The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's versions-filled // The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's version-released
// and version-released heard; nothing is reserved before the fill. // heard (design 47 H2 H-A-552: no fill is waited for).
reservedKV := process.AwaitBucket(ctx, js, conn, own.reserved, "no version is reserved: builds are made unreserved", logger.Printf) reservedKV := process.AwaitBucket(ctx, js, conn, own.reserved, "no version is reserved: builds are made unreserved", logger.Printf)
reserved := newReservations(awaitedReserved{awaitedVersions{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, b.Reconsider, logger.Printf) reserved := newReservations(awaitedReserved{awaitedState{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, logger.Printf)
// The index by digest and by version beside the reservations is written again once the state is bound (H-A-269 (1), H-A-271). // The index by digest and by version beside the reservations is written again once the state is bound (H-A-269 (1), H-A-271).
reservedKV.Ready(func(jetstream.KeyValue) { reserved.reindex(ctx) }) reservedKV.Ready(func(jetstream.KeyValue) { reserved.reindex(ctx) })
// Each artifact the holder says published at a reserved version is said as the seat mesh-builds' package-published (design 47 G §52). // Each artifact the holder says published at a reserved version is said as the seat mesh-builds' package-published (design 47 G §52).
@@ -254,17 +243,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
} }
// A package's number reserved is said as the seat mesh-builds' version-reserved, so the indexer re-pins at the reservation (§805). // A package's number reserved is said as the seat mesh-builds' version-reserved, so the indexer re-pins at the reservation (§805).
reserved.names = versions.NamesFrom(versions.EntriesOf(branches)) reserved.names = versions.NamesFrom(versions.EntriesOf(branches))
reserved.r.Names = reserved.names // a Go package's module path names its tag's directory (§796)
reserved.sayReserved = sayReservedOn(js, cred) reserved.sayReserved = sayReservedOn(js, cred)
b.Reserved = reserved b.Reserved = reserved
// A take-over of a series' reservation by another fingerprint withdraws the older build (H-A-225). // A take-over of a series' reservation by another fingerprint withdraws the older build (H-A-225).
reserved.withdraw = b.Withdraw reserved.withdraw = b.Withdraw
// The last versions-filled the stream keeps is read at the start (design 47 G §369, §372): a restart does not lose it. reserved.recordAgain = b.RecordAgain // a done build's digests its end did not record are recorded at the start (H-A-492)
reserved.readFilled(ctx, lastKeptOf(js, cred, logger.Printf), sleeps) // The versions' hand acts (builder_publish_again, builder_reserved_drop) come through reasks, as builder_build_again.
// A state bound later numbers the builds looked at without it. acts := versions.Acts{DropReserved: reserved.dropped}
versionsKV.Ready(func(jetstream.KeyValue) { b.Reconsider(ctx) })
// The versions' hand acts (builder_publish_again, builder_floor_again) come through reasks, as builder_build_again.
acts := versions.Acts{Numberer: numberer, DropReserved: reserved.dropped, Reconsider: b.Reconsider}
// A reserved version left unpublished is published again, by the builder on an event or by a person's tool (design 47 G // A reserved version left unpublished is published again, by the builder on an event or by a person's tool (design 47 G
// §588): its items on the work queue publishes, the module's own stream of its old streams section (design 47 H2 §793, H-A-454). // §588): its items on the work queue publishes, the module's own stream of its old streams section (design 47 H2 §793, H-A-454).
actedKV := process.AwaitBucket(ctx, js, conn, own.acted, "no version is published again on an event or by builder_publish_again", logger.Printf) actedKV := process.AwaitBucket(ctx, js, conn, own.acted, "no version is published again on an event or by builder_publish_again", logger.Printf)
@@ -273,7 +258,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk), Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk),
Unreleased: reserved.unreleasedWords, Logf: logger.Printf, Unreleased: reserved.unreleasedWords, Logf: logger.Printf,
Holders: holders, // a registry seat's holder from the seat-holders view, from the start (design 47 G A-416, A-416a) Holders: holders, // a registry seat's holder from the seat-holders view, from the start (design 47 G A-416, A-416a)
Started: time.Now()} // a build ended from now on is of the live class, sent first (H-A-290 (1)) Started: time.Now()} // a build ended from now on is of the live class (H-A-290 (1))
// A number a registry seat already holds is never reserved (H-A-275): read before reserving, through the seats' verb versions. // A number a registry seat already holds is never reserved (H-A-275): read before reserving, through the seats' verb versions.
reserved.r.HeldNumbers = func(ctx context.Context, module, fp string, refs []string) ([]string, error) { reserved.r.HeldNumbers = func(ctx context.Context, module, fp string, refs []string) ([]string, error) {
return republish.HeldNumbers(ctx, module, fp, refs, registryVersionsVia(calls.Call)) return republish.HeldNumbers(ctx, module, fp, refs, registryVersionsVia(calls.Call))
@@ -310,8 +295,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return reserved.r.Of(ctx, module, version) return reserved.r.Of(ctx, module, version)
}, },
republish: republish.Republish, endedWith: reserved.unreleased, republish: republish.Republish, endedWith: reserved.unreleased,
// A publish is asked again only while no published of it may be unheard and the registry's record lacks it (H-A-269 (2), H-A-272). // A publish is asked again while the registry's record lacks it (H-A-269 (2), H-A-272; H-A-514 addendum: no backlog count).
unheard: unheardVia(js, process.EventsStream, cred.EventConsumerName()),
judge: func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) { judge: func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) {
return republish.Held(ctx, v, registryVersionsVia(calls.Call)) return republish.Held(ctx, v, registryVersionsVia(calls.Call))
}, },
@@ -322,20 +306,22 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// A version that never publishes (withdrawn or taken over) has its publish item ended by the queue too (H-A-290 (2)). // A version that never publishes (withdrawn or taken over) has its publish item ended by the queue too (H-A-290 (2)).
republish.Ended = items.Ended republish.Ended = items.Ended
pq.take = items.take pq.take = items.take
reasksKV.Ready(func(jetstream.KeyValue) { items.AskAllDone(ctx) }) // At the start, a built reservation the catalog holds released is taken in as its version-released would (H-A-484 addendum),
wirePublishItems(reserved, items, awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}}, releasedKept) // before the publish items of the rest are asked.
reasksKV.Ready(func(jetstream.KeyValue) {
reserved.releasedAtStart(ctx)
items.AskAllDone(ctx)
})
wirePublishItems(reserved, items, awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, releasedKept)
acts.Republish = republish.Republish acts.Republish = republish.Republish
acts.PublishDrop = func(ctx context.Context, module, version, by, why string) (string, error) { acts.PublishDrop = func(ctx context.Context, module, version, by, why string) (string, error) {
return pq.drop(ctx, items, module, version, by, why) return pq.drop(ctx, items, module, version, by, why)
} }
acts.PublishFirst = func(ctx context.Context, module, version, _, _ string) (string, error) {
return pq.first(ctx, items, module, version)
}
// builder_reserve_done: a done trunk build that reserved none is given a version, and its publish queued as publish again does. // builder_reserve_done: a done trunk build that reserved none is given a version, and its publish queued as publish again does.
acts.ReserveDone = reserveDoneAct(b.ReserveDone, republish.Republish, logger.Printf) acts.ReserveDone = reserveDoneAct(b.ReserveDone, republish.Republish, logger.Printf)
// The operator is asked once a key's event builds are spent (design 47 G §568): the builder's asker on the seat operator-channel. // The operator is asked once a key's event builds are spent (design 47 G §568): the builder's asker on the seat operator-channel.
decided := &decisions{subject: oc.SubjectDecided(cred.Module)} decided := &decisions{subject: oc.SubjectDecided(cred.Module)}
retakeActed := awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}} retakeActed := awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}
asker := &operatorask.Asker[oc.Warrant]{Module: cred.Module, Call: calls.Call, Record: calls.Ask, Publish: publishVia(ctx, js), Subscribe: decided.hear(logger.Printf), asker := &operatorask.Asker[oc.Warrant]{Module: cred.Module, Call: calls.Call, Record: calls.Ask, Publish: publishVia(ctx, js), Subscribe: decided.hear(logger.Printf),
Contract: operatorask.Contract{Seat: oc.Seat, StateAsks: oc.StateAsks}, Contract: operatorask.Contract{Seat: oc.Seat, StateAsks: oc.StateAsks},
AskSubject: oc.AcceptSubjectAsk, DecidedSubject: oc.SubjectDecided} AskSubject: oc.AcceptSubjectAsk, DecidedSubject: oc.SubjectDecided}
@@ -472,11 +458,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// The seat mesh-artifact-sweep says artifacts-gone when it found a key's blob gone (issue 1937, ADR 0571 §2): the // The seat mesh-artifact-sweep says artifacts-gone when it found a key's blob gone (issue 1937, ADR 0571 §2): the
// builder's durable consumer on EVENTS, made by the grants part from the manifest's consumes. Where it is not there yet the builder says // builder's durable consumer on EVENTS, made by the grants part from the manifest's consumes. Where it is not there yet the builder says
// so; it still asks held at its start and at every module value. // so; it still asks held at its start and at every module value.
// The same consumer carries what wakes a floor (design 51 *The floor*): the indexer's take-in.taken (design 47 H H-A-116) and the
// condition keeper's condition-cleared.
floor := floorWake{b: b, waits: floorWaits, logf: logger.Printf}
// And the four registry seats' published, refused and removed (DLV-B4), which move a numbered version. // And the four registry seats' published, refused and removed (DLV-B4), which move a numbered version.
seatHeard := seatHearer{n: numberer, b: b, logf: logger.Printf, pub: pubs, res: reserved} seatHeard := seatHearer{b: b, logf: logger.Printf, pub: pubs, res: reserved}
// Each part takes the events it hears in turn; a handling over the setting slow-event is said with the part that took it // Each part takes the events it hears in turn; a handling over the setting slow-event is said with the part that took it
// (design 47 H2 §794; H-A-461 (2)). // (design 47 H2 §794; H-A-461 (2)).
slow, err := slowEvent() slow, err := slowEvent()
@@ -489,12 +472,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
{"what a node's engine reads", func(m jetstream.Msg) bool { return reads.heard(m, logger.Printf) }}, // manifest-reads-changed (ADR 0618 §4) {"what a node's engine reads", func(m jetstream.Msg) bool { return reads.heard(m, logger.Printf) }}, // manifest-reads-changed (ADR 0618 §4)
{"the toolchains reported", func(m jetstream.Msg) bool { return heardTools.Reported(ctx, m) }}, {"the toolchains reported", func(m jetstream.Msg) bool { return heardTools.Reported(ctx, m) }},
{"the toolchains running", func(m jetstream.Msg) bool { return heardTools.Running(ctx, m) }}, {"the toolchains running", func(m jetstream.Msg) bool { return heardTools.Running(ctx, m) }},
{"the floor", func(m jetstream.Msg) bool { return floor.heard(ctx, m) }},
{"the reservations", func(m jetstream.Msg) bool { return reserved.heard(ctx, m) }}, {"the reservations", func(m jetstream.Msg) bool { return reserved.heard(ctx, m) }},
{"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }}, {"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }},
} }
gone := eventTaker{"the artifacts gone", func(m jetstream.Msg) bool { heardGone(ctx, b, m, logger.Printf); return true }} gone := eventTaker{"the artifacts gone", func(m jetstream.Msg) bool { heardGone(ctx, b, m, logger.Printf); return true }}
events := func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) } // Each event goes to a worker of the name it carries, one name's events in order, the names side by side (H-A-514 addenda).
workers := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) }}
events := workers.take
// The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, the indexer's take-in.taken and // The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, the indexer's take-in.taken and
// manifest-reads-changed and the seat mesh-conditions' condition-cleared: seatEventPatterns); the owners' views events and the // manifest-reads-changed and the seat mesh-conditions' condition-cleared: seatEventPatterns); the owners' views events and the
// catalog half's catalog-revision and registration-changed and the gate's source-moved are the views reader's (a message has // catalog half's catalog-revision and registration-changed and the gate's source-moved are the views reader's (a message has
@@ -564,20 +548,16 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
b.SayUnbuildable(ctx) // at the start, once the first views are in: the plans no seat builds in one line (§795) b.SayUnbuildable(ctx) // at the start, once the first views are in: the plans no seat builds in one line (§795)
} }
branches.Changed = half.Changed(ctx) branches.Changed = half.Changed(ctx)
// A catalog revision the builder hears wakes a floor whose tags or requirements were silent (design 47 G A-119).
half.floor = func(ctx context.Context) {
(&floorWake{b: b, waits: floorWaits, logf: logger.Printf}).wake(ctx, versions.WakeRevision, "", "")
}
// All of the catalog half's wiring is set before the reader starts: its views are heard on the reader's goroutines from then. // All of the catalog half's wiring is set before the reader starts: its views are heard on the reader's goroutines from then.
reader.Start(ctx, js, cred, process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, views.StatusState), "builder_first_views reads nothing and builder_first_view_again is not heard", logger.Printf)) reader.Start(ctx, js, cred, process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, views.StatusState), "builder_first_views reads nothing and builder_first_view_again is not heard", logger.Printf))
// Every part has registered: the hub pulls the module's durable. Where the consumer is not there yet the builder says so // Every part has registered: the hub pulls the module's durable. Where the consumer is not there yet the builder says so
// and binds it at a later change (heard.Writer; ADR 0615 §5). // and binds it at a later change (heard.Writer; ADR 0615 §5).
_ = notHeard.Bind(eventsStream, sweep.EventArtifactsGone+", what wakes a floor, the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again", func() error { _ = notHeard.Bind(eventsStream, sweep.EventArtifactsGone+", the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again", func() error {
if err := hub.Start(ctx, js, cred); err != nil { if err := hub.Start(ctx, js, cred); err != nil {
return err return err
} }
// And the kept seat events it handles (the build seats' toolchain-reported, the seat mesh-catalog's versions-filled // And the kept seat events it handles (the build seats' toolchain-reported, the seat mesh-catalog's
// and version-released), each on its own stream: the tool runner reads its own twin there (lead answer A-397). // version-released), each on its own stream: the tool runner reads its own twin there (lead answer A-397).
hub.StartKept(ctx, js, cred) hub.StartKept(ctx, js, cred)
return nil return nil
}) })
@@ -624,7 +604,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
} }
return return
} }
pubs.ended(ctx, e)
} }
watchBounds(ctx, kv, each, found.notHeard(ctx), errs, logger.Printf) watchBounds(ctx, kv, each, found.notHeard(ctx), errs, logger.Printf)
}) })
@@ -8,8 +8,8 @@ import (
const namedTreePrefix = "named:" const namedTreePrefix = "named:"
// seatEventPatterns are the seats' events the builder's own handler takes off its durable consumer (its manifest's `consumes` of // seatEventPatterns are the seats' events the builder's own handler takes off its durable consumer (its manifest's `consumes` of
// them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, condition-cleared, the node-engine // them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, the node-engine
// seat's events, of the seat mesh-catalog, version-released and versions-filled, and the indexer's take-in.taken. The seat mesh-catalog's // seat's events, of the seat mesh-catalog, version-released. The seat mesh-catalog's
// catalog-revision and registration-changed and the seat mesh-delivery's source-moved are the views reader's (the branch // catalog-revision and registration-changed and the seat mesh-delivery's source-moved are the views reader's (the branch
// follower's), so no pattern here covers them: a message has one taker. // follower's), so no pattern here covers them: a message has one taker.
var seatEventPatterns = func() []string { var seatEventPatterns = func() []string {
@@ -18,9 +18,8 @@ var seatEventPatterns = func() []string {
"mesh-artifact-sweep", "mesh-conditions", "node-engine", "node-build-go", "node-build-image", "node-build-node"} { "mesh-artifact-sweep", "mesh-conditions", "node-engine", "node-build-go", "node-build-image", "node-build-node"} {
out = append(out, "mesh.seat."+seat+".event.>") out = append(out, "mesh.seat."+seat+".event.>")
} }
for _, event := range []string{meshcatalog.EventVersionReleased, meshcatalog.EventVersionsFilled} { for _, event := range []string{meshcatalog.EventVersionReleased} {
out = append(out, "mesh.seat."+meshcatalog.Seat+".event."+event, "mesh.seat."+meshcatalog.Seat+".event."+event+".>") out = append(out, "mesh.seat."+meshcatalog.Seat+".event."+event, "mesh.seat."+meshcatalog.Seat+".event."+event+".>")
} }
// And the indexer's take-in.taken, which wakes the floor (design 47 H H-A-116). return out
return append(out, takenInSubject)
}() }()
@@ -32,14 +32,11 @@ func TestTheNamesAreTheManifests(t *testing.T) {
t.Errorf("the builder reads %s, its manifest's reads are %v", read, m.Reads) t.Errorf("the builder reads %s, its manifest's reads are %v", read, m.Reads)
} }
} }
// The catalog half (design 47 G §348, §614) is followed through the seat, and no state of the indexer is; the indexer's // The catalog half (design 47 G §348, §614) is followed through the seat, and nothing of the indexer is: with the floor gone
// event take-in.taken wakes the floor (design 47 H H-A-116). // (design 47 H §756) not its take-in.taken either (H-A-116).
if !slices.Contains(m.Consumes, "mesh-delivery-indexer.take-in.taken") {
t.Errorf("the builder's floor wakes on no take-in.taken: its manifest consumes %v", m.Consumes)
}
for _, c := range m.Consumes { for _, c := range m.Consumes {
if strings.HasPrefix(c, "mesh-delivery-indexer.") && c != "mesh-delivery-indexer.take-in.taken" { if strings.HasPrefix(c, "mesh-delivery-indexer.") {
t.Errorf("the builder follows %s, an indexer state, its manifest consumes it", c) t.Errorf("the builder follows %s of the indexer, its manifest consumes it", c)
} }
} }
for _, view := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "seat:mesh-module-assigner.views.assignments"} { for _, view := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "seat:mesh-module-assigner.views.assignments"} {
@@ -51,7 +48,6 @@ func TestTheNamesAreTheManifests(t *testing.T) {
"mesh-build-go_steps": buildrun.StepsBucket("mesh-build-go"), "mesh-build-go_steps": buildrun.StepsBucket("mesh-build-go"),
ownBucketsOf("acme-builder").toolchainsHeard: "acme-builder_toolchains-heard", ownBucketsOf("acme-builder").toolchainsHeard: "acme-builder_toolchains-heard",
ownBucketsOf("acme-builder").bounds: "acme-builder_bounds", ownBucketsOf("acme-builder").bounds: "acme-builder_bounds",
ownBucketsOf("acme-builder").versions: "acme-builder_versions",
ownBucketsOf("acme-builder").instances: "acme-builder_instances", ownBucketsOf("acme-builder").instances: "acme-builder_instances",
} { } {
if want != got { if want != got {
@@ -2,9 +2,7 @@ package main
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
@@ -17,53 +15,15 @@ import (
) )
// publishes raises and clears the builder's findings of a publish that ended badly (versions/publish.go): a holder's // publishes raises and clears the builder's findings of a publish that ended badly (versions/publish.go): a holder's
// refused, a version unanswered past its bound, kept as a key of the state bounds with its own time to live, and a seat's // refused and a seat's outcome that does not read. A reserved version left unpublished is the reservation's bound (design 47
// outcome that does not read. // G §369, design 47 H §756: the numbered version's bound goes with the numbering from before G).
type publishes struct { type publishes struct {
bounds func() jetstream.KeyValue
versions versions.Versions
findings *findings findings *findings
bound time.Duration
logf func(string, ...any)
} }
// arm writes the version's bound when none stands, so a standing bound keeps its time. A bound that cannot be written // heard is told each holder's word: published clears the name's findings (publish-unanswered too, raised by a builder of
// would never end, so the version is publish-unanswered at once (review round 2): the finding says why. // before the change), refused raises publish-refused with the holder's reason.
func (p *publishes) arm(ctx context.Context, e versions.Entry) {
kv := p.bounds()
var err error
if kv == nil {
err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState)
} else if _, err = kv.Create(ctx, versions.PublishBoundKey(e.Name, e.Version), versions.EncodeBound("the publish of "+e.Name+"@"+e.Version+" to "+e.Seat, time.Now().Add(p.bound)), jetstream.KeyTTL(p.bound)); errors.Is(err, jetstream.ErrKeyExists) {
err = nil
}
if err == nil {
return
}
p.logf("the publish bound of %s@%s is not written, so it is raised unanswered now: %v", e.Name, e.Version, err)
p.unanswered(ctx, e, fmt.Sprintf("its bound could not be written (%v), so the builder cannot wait on the holder's word", err))
}
// unanswered raises publish-unanswered about e's name, saying why.
func (p *publishes) unanswered(ctx context.Context, v versions.Entry, why string) {
p.findings.raise(ctx, finding{kind: versions.PublishUnanswered, scope: meshconditionsclient.ScopeModule, id: v.Name,
summary: fmt.Sprintf("%s said neither published nor refused of %s@%s: %s", v.Seat, v.Name, v.Version, why),
headline: "A registry seat did not answer a publish",
explanation: "The builder built and numbered " + v.Name + " " + v.Version + " and asked " + v.Seat + " to publish it; no word of its holder is known, so the build says done while the version may not be in the registry.",
resolved: "That version is published, or a later version of " + v.Name + " is.",
needs: "a look at the holder of " + v.Seat + " (its health and log); builder_publish_again asks the publish again."})
}
// heard is told each holder's word the numberer took in: published clears the name's findings, refused raises
// publish-refused with the holder's reason, and either ends the version's bound.
func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Outcome) { func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Outcome) {
if o.Version != "" {
if kv := p.bounds(); kv != nil {
if err := kv.Delete(ctx, versions.PublishBoundKey(o.Name, o.Version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
p.logf("the publish bound of %s@%s is not ended: %v", o.Name, o.Version, err)
}
}
}
switch event { switch event {
case versions.HeardPublished: case versions.HeardPublished:
p.findings.clear(ctx, versions.PublishRefused, meshconditionsclient.ScopeModule, o.Name) p.findings.clear(ctx, versions.PublishRefused, meshconditionsclient.ScopeModule, o.Name)
@@ -78,7 +38,7 @@ func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Ou
headline: "A registry seat refused a publish", headline: "A registry seat refused a publish",
explanation: "The builder built and numbered " + o.Name + " " + o.Version + ", and the holder of " + seat + " refused to store it, so that version is not in the registry.", explanation: "The builder built and numbered " + o.Name + " " + o.Version + ", and the holder of " + seat + " refused to store it, so that version is not in the registry.",
resolved: "That version is published, or a later version of " + o.Name + " is.", resolved: "That version is published, or a later version of " + o.Name + " is.",
needs: "builder_versions shows the version and why; builder_publish_again publishes it again once the cause is mended."}) needs: "builder_reserved shows the version and why; builder_publish_again publishes it again once the cause is mended."})
} }
} }
@@ -96,24 +56,6 @@ func (p *publishes) read(ctx context.Context, seat string) {
p.findings.clear(ctx, versions.SeatOutcomeUnread, meshconditionsclient.ScopeModule, seat) p.findings.clear(ctx, versions.SeatOutcomeUnread, meshconditionsclient.ScopeModule, seat)
} }
// ended is told each change of the state bounds: a bound whose time ended (the bus's marker) on a version still numbered
// raises publish-unanswered.
func (p *publishes) ended(ctx context.Context, e jetstream.KeyValueEntry) {
key, ok := versions.PublishBoundOf(e.Key())
if e.Operation() != jetstream.KeyValuePurge || !ok {
return
}
raw, _, found, err := p.versions.Store.Get(ctx, key)
if err != nil || !found {
return
}
v, err := versions.Decode(raw)
if err != nil || v.State != versions.Numbered {
return
}
p.unanswered(ctx, v, fmt.Sprintf("nothing within %s of its build", p.bound))
}
// watchBounds watches the state bounds, handing each change to each: a watch that cannot start loses every bound's end, // watchBounds watches the state bounds, handing each change to each: a watch that cannot start loses every bound's end,
// so it is the finding family-not-heard naming the state until a later start watches it (review round 2). // so it is the finding family-not-heard naming the state until a later start watches it (review round 2).
func watchBounds(ctx context.Context, kv jetstream.KeyValue, each func(jetstream.KeyValueEntry), w heard.Writer, errs chan<- error, logf func(string, ...any)) { func watchBounds(ctx context.Context, kv jetstream.KeyValue, each func(jetstream.KeyValueEntry), w heard.Writer, errs chan<- error, logf func(string, ...any)) {
@@ -22,19 +22,21 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/testbus"
"git.novox.be/novox/mesh-sdk/go/views" "git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-builder/internal/versions" "mesh-delivery-builder/internal/versions"
) )
// Design 47 H2 §793 (whole, against the bus): the builder's work queue publishes, its pull consumers made as it learns a holder. // Design 47 H2 §793 (whole, against the bus): the builder's work queue publishes, one pull consumer made as it learns a holder
// A live publish enqueued behind 100 again items while the builder was away is sent first; a dropped item is never sent, and // (H-A-483 and its addenda), the class durables of an earlier release retired. No item is lost, a failed send comes back after
// put again within the duplicates window is not stored; the move of the old state run twice puts each item once, and the // its pause behind an item put meanwhile, and a dropped item never comes back; 100 again items and a live one put while the
// builder removes the old state's bucket itself (H-A-461 (1)). The seat mesh-builds' verb publish-queue reads the stream: counts // builder was away are all sent, the dropped one never, and put again within the duplicates window it is not stored; the move
// per holder and class, the oldest and newest, the live item listed first (H-A-454). Then §796's tag at another commit, its // of the old state run twice puts each item once, and the builder removes the old state's bucket itself (H-A-461 (1)). The seat
// reservation's version-reserved waited on by name (§821), and // mesh-builds' verb publish-queue reads the stream: counts per holder and class, the oldest and newest, the items listed in
// §794's backlog held six minutes, as steps (H-A-453 (3)). // stream order (H-A-454; H-A-483, third addendum). Then §796's tag at another commit, its reservation's version-reserved waited on by name (§821), and §794's
func TestThePublishQueueSendsLiveFirstAndNeverADroppedItem(t *testing.T) { // backlog held six minutes, as steps (H-A-453 (3)).
func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
b := startBed(t) b := startBed(t)
ctx := b.ctx ctx := b.ctx
// The stream as the manifest's old streams section declares it: the module's own, retention work-queue, duplicates 24 hours. // The stream as the manifest's old streams section declares it: the module's own, retention work-queue, duplicates 24 hours.
@@ -43,281 +45,425 @@ func TestThePublishQueueSendsLiveFirstAndNeverADroppedItem(t *testing.T) {
Retention: jetstream.WorkQueuePolicy, Discard: jetstream.DiscardNew, Duplicates: 24 * time.Hour, MaxAge: 7 * 24 * time.Hour}); err != nil { Retention: jetstream.WorkQueuePolicy, Discard: jetstream.DiscardNew, Duplicates: 24 * time.Hour, MaxAge: 7 * 24 * time.Hour}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} // One consumer per holder (H-A-483 and its addenda): the holder's class durables of an earlier release are retired, the item
var mu sync.Mutex // one of them held unacknowledged reaches the one consumer; no item is lost; a failed send comes back after its pause, and a
var sent []string // live item put while it waits is sent before it returns; a dropped item never comes back.
published := map[string]bool{} // the modules whose publish is heard t.Run("one consumer", func(t *testing.T) {
sentCh := make(chan string, 200) const holder, pause = "paused", 3 * time.Second // the pause is far longer than a send of an item put now
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: time.Second, PauseMax: time.Minute, Tries: 5}, bound := testbus.SetupBound(t)
now: time.Now, logf: t.Logf, kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) { type send struct {
module string
at time.Time
}
var mu sync.Mutex
published, failed := map[string]bool{}, map[string]bool{}
sentCh := make(chan send, 16)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: pause, PauseMax: time.Minute, Tries: 5},
now: time.Now, logf: t.Logf,
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
mu.Lock()
defer mu.Unlock()
return versions.ReservedVersion{Module: m, Version: v, Artifacts: map[string]string{m + ":a": "sha256:a"}, Published: map[string]bool{m + ":a": published[m]}, BuiltAt: time.Now()}, true, nil
},
send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate {
sentCh <- send{q.Module, time.Now()}
mu.Lock()
defer mu.Unlock()
if (q.Module == "fail" || q.Module == "dropme") && !failed[q.Module] { // the first send of each fails
failed[q.Module] = true
return versions.SendFate{Failed: "the registry is down"}
}
published[q.Module] = true
return versions.SendFate{Sent: true}
}}
pq := &publishQueue{js: b.js, ackWait: time.Minute, logf: t.Logf, take: items.take, binding: publishesOf("mesh-delivery-builder")}
put := func(module, class string) {
q := versions.QueuedPublish{V: 1, Holder: holder, Module: module, Version: "0.1.0", Artifacts: map[string]string{module + ":a": "sha256:a"}, Class: class, Queued: time.Now()}
data, _ := json.Marshal(q)
if _, err := b.js.Publish(ctx, pq.subject(bind, q), data); err != nil {
t.Fatal(err)
}
}
hear := func() { // each publish sent is heard: its item acknowledged once it is held
mu.Lock() mu.Lock()
defer mu.Unlock() var done []string
return versions.ReservedVersion{Module: m, Version: v, Artifacts: map[string]string{m + ":a": "sha256:a"}, Published: map[string]bool{m + ":a": published[m]}, BuiltAt: time.Now()}, true, nil for m, ok := range published {
}, if ok {
send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate { done = append(done, m)
mu.Lock() }
sent = append(sent, q.Module) }
mu.Unlock() mu.Unlock()
sentCh <- q.Module for _, m := range done {
return versions.SendFate{Sent: true} items.heard(ctx, m, "0.1.0")
}} }
pq := &publishQueue{js: b.js, ackWait: time.Minute, logf: t.Logf, take: items.take, binding: publishesOf("mesh-delivery-builder")} }
item := func(module, class string) versions.QueuedPublish { next := func() send {
return versions.QueuedPublish{V: 1, Holder: "oci", Module: module, Version: "0.1.0", Artifacts: map[string]string{module + ":a": "sha256:a"}, Class: class, Queued: time.Now()} t.Helper()
} select {
away := func(q versions.QueuedPublish) { // put while the builder was away: no holder learnt, nothing pulled case s := <-sentCh:
data, _ := json.Marshal(q) hear()
if _, err := b.js.Publish(ctx, pq.subject(bind, q), data, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version))); err != nil { return s
case <-time.After(bound):
t.Fatal("no item was sent within the level's set-up share")
}
return send{}
}
// The two class durables an earlier release made, the live one holding an item given and not acknowledged.
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder) + "-" + class,
FilterSubject: bind.Subject + ".publish." + holder + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Hour}); err != nil {
t.Fatal(err)
}
}
put("given", versions.PublishClassLive)
old, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder)+"-"+versions.PublishClassLive)
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
} if m, err := old.Next(); err != nil {
for i := range 100 { t.Fatal(err)
away(item(fmt.Sprintf("a%03d", i), versions.PublishClassStart)) } else if md, _ := m.Metadata(); md.NumDelivered != 1 {
} t.Fatalf("the old live durable gave %+v", md)
away(item("dropme", versions.PublishClassStart))
away(item("live", versions.PublishClassLive))
if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil {
t.Fatalf("drop: %v", err)
} else {
t.Log(answer)
}
if dup, err := pq.put(ctx, item("dropme", versions.PublishClassStart)); err != nil || !dup {
t.Errorf("a dropped item put again within the window: duplicate %v (%v), want it not stored", dup, err)
}
raw, err := publishQueueVerb(ctx, pq)("op@node", json.RawMessage(`{}`))
if a, ok := raw.(meshbuilds.PublishQueueAnswer); err != nil || !ok || a.Total != 101 || len(a.Counts) != 2 || a.Counts[0].Class != versions.PublishClassStart ||
a.Counts[0].Count != 100 || a.Counts[1].Count != 1 || a.Counts[0].Oldest.After(a.Counts[0].Newest) || len(a.Queue) != versions.PublishQueueListCap ||
a.Queue[0].Module != "live" || a.Capped {
t.Errorf("publish-queue answered %+v (%v), want 101 items, oci's 100 again and 1 live, fifty listed, the live first", raw, err)
}
if err := pq.learnAll(ctx); err != nil {
t.Fatal(err)
}
select {
case first := <-sentCh:
if first != "live" {
t.Errorf("the first item sent is %s, want the live one, enqueued behind 100 again items", first)
} }
case <-time.After(30 * time.Second): pq.learn(ctx, holder)
t.Fatal("nothing was sent") stream, err := b.js.Stream(ctx, bind.Stream)
} if err != nil {
for range 4 { // the again items in flight: at most four held unacknowledged, their publish unheard t.Fatal(err)
select { }
case <-sentCh: var names []string
case <-time.After(30 * time.Second): for n := range stream.ConsumerNames(ctx).Name() {
t.Fatal("the again items were not sent") if strings.HasPrefix(n, publishesConsumer(holder)) {
names = append(names, n)
}
}
if !slices.Equal(names, []string{publishesConsumer(holder)}) {
t.Fatalf("the consumers of %s are %v, want only %s: the class durables retired", holder, names, publishesConsumer(holder))
}
if s := next(); s.module != "given" {
t.Fatalf("sent %s first, want the item the old durable held unacknowledged", s.module)
}
put("fail", versions.PublishClassStart)
put("dropme", versions.PublishClassStart)
var firstFail time.Time
for range 2 {
if s := next(); s.module == "fail" {
firstFail = s.at
}
}
put("live", versions.PublishClassLive) // put while both failed items wait out their pause
if s := next(); s.module != "live" {
t.Fatalf("sent %s, want the live item put while the failed ones wait their pause", s.module)
}
if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil {
t.Fatalf("drop: %v", err)
} else {
t.Log(answer)
}
if s := next(); s.module != "fail" || s.at.Sub(firstFail) < pause {
t.Fatalf("sent %s %s after the failed send, want fail again after its pause %s", s.module, s.at.Sub(firstFail), pause)
}
// Every item is acknowledged and the dropped one is gone: nothing is left to come back.
c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder))
if err != nil {
t.Fatal(err)
}
st, err := b.js.Stream(ctx, bind.Stream)
if err != nil {
t.Fatal(err)
}
for deadline := time.Now().Add(bound); ; {
hear()
info, err := c.Info(ctx)
if err != nil {
t.Fatal(err)
}
sinfo, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish."+holder+".>"))
if err != nil {
t.Fatal(err)
}
if info.NumAckPending == 0 && info.NumPending == 0 && len(sinfo.State.Subjects) == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("the queue of %s holds %v, its consumer %d pending and %d unacknowledged: want every item acknowledged and the dropped one gone", holder, sinfo.State.Subjects, info.NumPending, info.NumAckPending)
}
select {
case s := <-sentCh:
t.Fatalf("sent %s again, want nothing more", s.module)
case <-time.After(10 * time.Millisecond):
}
}
})
t.Run("the queue, the move, tags and backlog", func(t *testing.T) {
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
var mu sync.Mutex
var sent []string
published := map[string]bool{} // the modules whose publish is heard
sentCh := make(chan string, 200)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: time.Second, PauseMax: time.Minute, Tries: 5},
now: time.Now, logf: t.Logf,
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
mu.Lock()
defer mu.Unlock()
return versions.ReservedVersion{Module: m, Version: v, Artifacts: map[string]string{m + ":a": "sha256:a"}, Published: map[string]bool{m + ":a": published[m]}, BuiltAt: time.Now()}, true, nil
},
send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate {
mu.Lock()
sent = append(sent, q.Module)
mu.Unlock()
sentCh <- q.Module
return versions.SendFate{Sent: true}
}}
pq := &publishQueue{js: b.js, ackWait: time.Minute, logf: t.Logf, take: items.take, binding: publishesOf("mesh-delivery-builder")}
item := func(module, class string) versions.QueuedPublish {
return versions.QueuedPublish{V: 1, Holder: "oci", Module: module, Version: "0.1.0", Artifacts: map[string]string{module + ":a": "sha256:a"}, Class: class, Queued: time.Now()}
}
away := func(q versions.QueuedPublish) { // put while the builder was away: no holder learnt, nothing pulled
data, _ := json.Marshal(q)
if _, err := b.js.Publish(ctx, pq.subject(bind, q), data, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version))); err != nil {
t.Fatal(err)
}
}
for i := range 100 {
away(item(fmt.Sprintf("a%03d", i), versions.PublishClassStart))
}
away(item("dropme", versions.PublishClassStart))
away(item("live", versions.PublishClassLive))
if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil {
t.Fatalf("drop: %v", err)
} else {
t.Log(answer)
}
if dup, err := pq.put(ctx, item("dropme", versions.PublishClassStart)); err != nil || !dup {
t.Errorf("a dropped item put again within the window: duplicate %v (%v), want it not stored", dup, err)
}
raw, err := publishQueueVerb(ctx, pq)("op@node", json.RawMessage(`{}`))
if a, ok := raw.(meshbuilds.PublishQueueAnswer); err != nil || !ok || a.Total != 101 || len(a.Counts) != 2 || a.Counts[0].Class != versions.PublishClassStart ||
a.Counts[0].Count != 100 || a.Counts[1].Count != 1 || a.Counts[0].Oldest.After(a.Counts[0].Newest) || len(a.Queue) != versions.PublishQueueListCap ||
a.Queue[0].Module != "a000" || a.Capped {
t.Errorf("publish-queue answered %+v (%v), want 101 items, oci's 100 again and 1 live, fifty listed in stream order, a000 first", raw, err)
}
if err := pq.learnAll(ctx); err != nil {
t.Fatal(err)
}
for range 4 { // the items in flight: at most four held unacknowledged, their publish unheard
select {
case <-sentCh:
case <-time.After(30 * time.Second):
t.Fatal("the again items were not sent")
}
}
deadline := time.After(60 * time.Second)
for { // each publish sent is heard: its item acknowledged, the next sent
mu.Lock()
n, done := len(sent), slices.Clone(sent)
for _, m := range done {
published[m] = true
}
mu.Unlock()
if n >= 101 {
break
}
for _, m := range done {
items.heard(ctx, m, "0.1.0")
}
select {
case <-sentCh:
case <-deadline:
t.Fatalf("sent %d of 101", n)
}
} }
}
deadline := time.After(60 * time.Second)
for { // each publish sent is heard: its item acknowledged, the next sent
mu.Lock() mu.Lock()
n, done := len(sent), slices.Clone(sent) if slices.Contains(sent, "dropme") || len(sent) != 101 {
for _, m := range done { t.Errorf("sent %d items (dropme among them: %v), want the 101 and never the dropped one", len(sent), slices.Contains(sent, "dropme"))
published[m] = true
} }
mu.Unlock() mu.Unlock()
if n >= 101 {
break // The move of the old state, run twice, puts each item once (at another holder, so the pull of oci is not asked).
old, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket("mesh-delivery-builder", versions.PublishQueueState)})
if err != nil {
t.Fatal(err)
} }
for _, m := range done { var tagsWritten []string
items.heard(ctx, m, "0.1.0") call := func(tool string, body any) (json.RawMessage, error) {
switch tool {
case "seat:" + gitseat.Seat + "." + gitseat.VerbTags: // m4's 0.2.0 is tagged at another commit, never read (H-A-494)
tagsWritten = append(tagsWritten, "read "+body.(gitseat.TagsInput).Prefix)
return json.Marshal(gitseat.TagsAnswer{Form: 2, Tags: []gitseat.Tag{{Tag: "modules/m4/v0.2.0", Commit: "c-other"}}})
case "seat:" + gitseat.Seat + ".tag":
tagsWritten = append(tagsWritten, body.(gitseat.TagInput).Tag+"@"+body.(gitseat.TagInput).Commit)
return json.Marshal(gitseat.TagAnswer{Performed: true})
}
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}
found := &memFindings{vals: map[string][]byte{}}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, t.Logf)
type oldItem struct {
key string
raw []byte
}
var olds []oldItem
for _, m := range []string{"m1", "m2", "m3"} {
v, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "src2:" + m})
if err != nil {
t.Fatal(err)
}
if err := rv.Built(ctx, m, v.Version, map[string]string{m + ":a": "sha256:a"}, nil); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(versions.QueuedPublish{V: 1, Holder: "go", Module: m, Version: v.Version, Artifacts: map[string]string{m + ":a": "sha256:a"}, Class: "asked-again-at-start"})
if _, err := old.Put(ctx, versions.QueueKey("go", m, v.Version), raw); err != nil {
t.Fatal(err)
}
olds = append(olds, oldItem{versions.QueueKey("go", m, v.Version), raw})
}
rp := &versions.Republisher{Reserved: rv.r, Put: func(ctx context.Context, q versions.QueuedPublish) (bool, error) {
data, _ := json.Marshal(q)
ack, err := b.js.Publish(ctx, pq.subject(bind, q), data, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version)))
if err != nil {
return false, err
}
return ack.Duplicate, nil
}, Started: time.Now(), Logf: t.Logf}
oldBucket := builds.StateBucket("mesh-delivery-builder", versions.PublishQueueState)
moveOld(ctx, b.js, oldBucket, rp, t.Logf)
if _, err := b.js.KeyValue(ctx, oldBucket); !errors.Is(err, jetstream.ErrBucketNotFound) {
t.Errorf("after the move the old state's bucket answers %v, want it removed by the builder (H-A-461 (1))", err)
}
// A start that stopped before the removal moves the same items again: the duplicates window keeps each once.
again, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: oldBucket})
if err != nil {
t.Fatal(err)
}
for _, e := range olds {
if _, err := again.Put(ctx, e.key, e.raw); err != nil {
t.Fatal(err)
}
}
moveOld(ctx, b.js, oldBucket, rp, t.Logf)
moveOld(ctx, b.js, oldBucket, rp, t.Logf) // no bucket left: nothing moves
if _, err := b.js.KeyValue(ctx, oldBucket); !errors.Is(err, jetstream.ErrBucketNotFound) {
t.Errorf("after the second move the old state's bucket answers %v, want it removed", err)
}
st, err := b.js.Stream(ctx, bind.Stream)
if err != nil {
t.Fatal(err)
}
info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish.go.>"))
if err != nil {
t.Fatal(err)
}
if len(info.State.Subjects) != 3 || info.State.Subjects[bind.Subject+".publish.go.again.m1.0=2E1=2E0"] != 1 {
t.Errorf("the move run twice left %v on the work queue: want each of the three once, as again", info.State.Subjects)
}
// Design 47 H2 H-A-494: no git tag is read before a reserve nor written at a release: m4's 0.2.0, which the seat git would
// answer tagged at another commit, is reserved, no finding raised, and its version-released writes no tag.
// Design 47 H2 §821, §805: the reservation is said as the seat mesh-builds' version-reserved, said as the process says it
// (sayReservedOn), and waited on by the seat and the event's name.
rv.names = func(context.Context, string, string) (string, bool, error) {
return "git.example/o/r/modules/m4", true, nil
}
rv.sayReserved = sayReservedOn(b.js, process.Account{Module: builds.BuilderModule, Node: "n1"})
said, err := nats.Connect(b.srvURL, nats.UserInfo("ctl", "pw"))
if err != nil {
t.Fatal(err)
}
defer said.Close()
reservedCh := make(chan *nats.Msg, 4)
rs, err := said.ChanSubscribe(meshbuilds.SubjectVersionReserved, reservedCh)
if err != nil {
t.Fatal(err)
}
defer rs.Unsubscribe()
if err := said.Flush(); err != nil {
t.Fatal(err)
}
v4, err := rv.Reserve(ctx, "m4", "0.2", []string{"m4:lib"}, versions.Source{Fingerprint: "src2:m4",
Repository: "o/r", Commit: "c-mine", Branch: "main", CatalogRevision: 1})
elsewhere := views.FindingKey(meshconditionsclient.ScopeModule, "m4", versions.VersionTaggedElsewhere)
if _, raised := found.vals[elsewhere]; err != nil || v4.Version != "0.2.0" || v4.Tag != "" || raised {
t.Fatalf("m4 reserved %+v (%v), %s raised %v: want 0.2.0 naming no tag, no tag read and no finding", v4, err, elsewhere, raised)
} }
select { select {
case <-sentCh: case m := <-reservedCh:
case <-deadline: ev, _, err := meshbuilds.DecodeVersionReservedEvent(m.Data)
t.Fatalf("sent %d of 101", n) if err != nil || ev.Module != "m4" || ev.Artifact != "m4:lib" || ev.Path != "git.example/o/r/modules/m4" || ev.Version != "0.2.0" ||
ev.Fingerprint != "src2:m4" || ev.Revision != "main.1" || m.Header.Get("x-source") != builds.BuilderModule {
t.Errorf("version-reserved = %+v (%v) from %q, want m4:lib at 0.2.0, its path, fingerprint src2:m4 and revision main.1, said by the builder", ev, err, m.Header.Get("x-source"))
}
case <-time.After(10 * time.Second):
t.Fatal("no version-reserved of m4's reservation within 10 s on " + meshbuilds.SubjectVersionReserved)
}
catalogEvents, err := b.js.StreamNameBySubject(ctx, meshcatalog.SubjectVersionReleased) // the bed's stream of the catalog's events
if err != nil {
t.Fatal(err)
}
evs, err := b.js.CreateOrUpdateConsumer(ctx, catalogEvents, jetstream.ConsumerConfig{Durable: "builder-events", AckPolicy: jetstream.AckExplicitPolicy,
FilterSubject: meshcatalog.SubjectVersionReleased, DeliverPolicy: jetstream.DeliverNewPolicy})
if err != nil {
t.Fatal(err)
}
next := func(module, version string) jetstream.Msg {
t.Helper()
data, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: module, Version: version})
if _, err := b.js.Publish(ctx, meshcatalog.SubjectVersionReleased, data); err != nil {
t.Fatal(err)
}
m, err := evs.Next(jetstream.FetchMaxWait(10 * time.Second))
if err != nil {
t.Fatal(err)
}
return m
}
if !rv.heard(ctx, next("m4", "0.2.0")) {
t.Fatal("the reservations did not take version-released")
}
if _, standing, _ := rv.r.Of(ctx, "m4", "0.2.0"); standing || len(tagsWritten) != 0 {
t.Errorf("after version-released m4 0.2.0 standing %v, tags read or written %v: want it released and no tag read or written", standing, tagsWritten)
} }
}
mu.Lock()
if slices.Contains(sent, "dropme") || len(sent) != 101 {
t.Errorf("sent %d items (dropme among them: %v), want the 101 and never the dropped one", len(sent), slices.Contains(sent, "dropme"))
}
mu.Unlock()
// The move of the old state, run twice, puts each item once (at another holder, so the pull of oci is not asked). // Design 47 H2 §794 (whole, H-A-453 (3), H-A-462): a message the builder's handler leaves unacknowledged is kept on its
old, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket("mesh-delivery-builder", versions.PublishQueueState)}) // consumer's ledger in the state consumers on the bus; held six minutes, the health names that backlog, and within five
if err != nil { // minutes it does not.
t.Fatal(err) consumers, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, process.ConsumersState)})
}
var tagsWritten []string
call := func(tool string, body any) (json.RawMessage, error) {
switch tool {
case "seat:" + gitseat.Seat + "." + gitseat.VerbTags: // m4's 0.2.0 is tagged at another commit (§796)
return json.Marshal(gitseat.TagsAnswer{Form: 2, Tags: []gitseat.Tag{{Tag: "modules/m4/v0.2.0", Commit: "c-other"}}})
case "seat:" + gitseat.Seat + ".tag":
tagsWritten = append(tagsWritten, body.(gitseat.TagInput).Tag+"@"+body.(gitseat.TagInput).Commit)
return json.Marshal(gitseat.TagAnswer{Performed: true})
}
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}
found := &memFindings{vals: map[string][]byte{}}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, nil, t.Logf)
rv.filled.Store(true)
type oldItem struct {
key string
raw []byte
}
var olds []oldItem
for _, m := range []string{"m1", "m2", "m3"} {
v, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "src2:" + m})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := rv.Built(ctx, m, v.Version, map[string]string{m + ":a": "sha256:a"}, nil); err != nil { held := time.Now()
t.Fatal(err) hub := &oneHandler{}
aged := agedHub{hub: hub, ledgers: &ledgers{logf: t.Logf, now: func() time.Time { return held },
sink: consumersSink(process.AwaitBucket(ctx, b.js, nil, builds.StateBucket(builds.BuilderModule, process.ConsumersState), "", t.Logf))}}
_ = aged.Handle(meshcatalog.SubjectVersionReleased, func(m jetstream.Msg) { _ = m.Nak() }) // a handler standing still: asked again
hub.handle(next("m5", "0.1.0"))
state := versions.Reader{Keys: func() ([]string, error) {
l, err := consumers.ListKeys(ctx)
if err != nil {
return nil, err
}
var keys []string
for k := range l.Keys() {
keys = append(keys, k)
}
return keys, nil
}, Get: func(k string) (json.RawMessage, bool, error) {
e, err := consumers.Get(ctx, k)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
return e.Value(), true, nil
}}
if a := versions.BuilderHealth(state, held.Add(6*time.Minute), 5*time.Minute); a.Healthy || !strings.Contains(a.Why, "builder-events (its oldest unacknowledged message waits 6m0s") {
t.Errorf("the health with a backlog held six minutes = %+v, want unhealthy naming builder-events", a)
} }
raw, _ := json.Marshal(versions.QueuedPublish{V: 1, Holder: "go", Module: m, Version: v.Version, Artifacts: map[string]string{m + ":a": "sha256:a"}, Class: "asked-again-at-start"}) if a := versions.BuilderHealth(state, held.Add(4*time.Minute), 5*time.Minute); !a.Healthy {
if _, err := old.Put(ctx, versions.QueueKey("go", m, v.Version), raw); err != nil { t.Errorf("the health four minutes in = %+v, want healthy", a)
t.Fatal(err)
} }
olds = append(olds, oldItem{versions.QueueKey("go", m, v.Version), raw}) })
}
rp := &versions.Republisher{Reserved: rv.r, Put: func(ctx context.Context, q versions.QueuedPublish) (bool, error) {
data, _ := json.Marshal(q)
ack, err := b.js.Publish(ctx, pq.subject(bind, q), data, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version)))
if err != nil {
return false, err
}
return ack.Duplicate, nil
}, Started: time.Now(), Logf: t.Logf}
oldBucket := builds.StateBucket("mesh-delivery-builder", versions.PublishQueueState)
moveOld(ctx, b.js, oldBucket, rp, t.Logf)
if _, err := b.js.KeyValue(ctx, oldBucket); !errors.Is(err, jetstream.ErrBucketNotFound) {
t.Errorf("after the move the old state's bucket answers %v, want it removed by the builder (H-A-461 (1))", err)
}
// A start that stopped before the removal moves the same items again: the duplicates window keeps each once.
again, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: oldBucket})
if err != nil {
t.Fatal(err)
}
for _, e := range olds {
if _, err := again.Put(ctx, e.key, e.raw); err != nil {
t.Fatal(err)
}
}
moveOld(ctx, b.js, oldBucket, rp, t.Logf)
moveOld(ctx, b.js, oldBucket, rp, t.Logf) // no bucket left: nothing moves
if _, err := b.js.KeyValue(ctx, oldBucket); !errors.Is(err, jetstream.ErrBucketNotFound) {
t.Errorf("after the second move the old state's bucket answers %v, want it removed", err)
}
st, err := b.js.Stream(ctx, bind.Stream)
if err != nil {
t.Fatal(err)
}
info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish.go.>"))
if err != nil {
t.Fatal(err)
}
if len(info.State.Subjects) != 3 || info.State.Subjects[bind.Subject+".publish.go.again.m1.0=2E1=2E0"] != 1 {
t.Errorf("the move run twice left %v on the work queue: want each of the three once, as again", info.State.Subjects)
}
// Design 47 H2 §796 (whole, H-A-453 (3)): a module's tags are read before it reserves; a number whose tag stands at another
// commit is skipped, the next number taken and version-tagged-elsewhere raised; the release tags <directory>/v<version> at
// the build's commit, and the module's version-released clears the finding.
rv.r.Names = func(context.Context, string, string) (string, bool, error) {
return "git.example/o/r/modules/m4", true, nil
}
// Design 47 H2 §821, §805: the reservation is said as the seat mesh-builds' version-reserved, said as the process says it
// (sayReservedOn), and waited on by the seat and the event's name.
rv.names, rv.sayReserved = rv.r.Names, sayReservedOn(b.js, process.Account{Module: builds.BuilderModule, Node: "n1"})
said, err := nats.Connect(b.srvURL, nats.UserInfo("ctl", "pw"))
if err != nil {
t.Fatal(err)
}
defer said.Close()
reservedCh := make(chan *nats.Msg, 4)
rs, err := said.ChanSubscribe(meshbuilds.SubjectVersionReserved, reservedCh)
if err != nil {
t.Fatal(err)
}
defer rs.Unsubscribe()
if err := said.Flush(); err != nil {
t.Fatal(err)
}
v4, err := rv.Reserve(ctx, "m4", "0.2", []string{"m4:lib"}, versions.Source{Fingerprint: "src2:m4", GoPackage: true, GoArtifact: "lib",
Repository: "o/r", Commit: "c-mine", Branch: "main", CatalogRevision: 1})
elsewhere := views.FindingKey(meshconditionsclient.ScopeModule, "m4", versions.VersionTaggedElsewhere)
if _, raised := found.vals[elsewhere]; err != nil || v4.Version != "0.2.1" || v4.Tag != "modules/m4/v0.2.1" || !raised {
t.Fatalf("m4 reserved %+v (%v), %s raised %v: want 0.2.1 past 0.2.0's tag at another commit, its tag modules/m4/v0.2.1, and the finding", v4, err, elsewhere, raised)
}
select {
case m := <-reservedCh:
ev, _, err := meshbuilds.DecodeVersionReservedEvent(m.Data)
if err != nil || ev.Module != "m4" || ev.Artifact != "m4:lib" || ev.Path != "git.example/o/r/modules/m4" || ev.Version != "0.2.1" ||
ev.Fingerprint != "src2:m4" || ev.Revision != "main.1" || m.Header.Get("x-source") != builds.BuilderModule {
t.Errorf("version-reserved = %+v (%v) from %q, want m4:lib at 0.2.1, its path, fingerprint src2:m4 and revision main.1, said by the builder", ev, err, m.Header.Get("x-source"))
}
case <-time.After(10 * time.Second):
t.Fatal("no version-reserved of m4's reservation within 10 s on " + meshbuilds.SubjectVersionReserved)
}
catalogEvents, err := b.js.StreamNameBySubject(ctx, meshcatalog.SubjectVersionReleased) // the bed's stream of the catalog's events
if err != nil {
t.Fatal(err)
}
evs, err := b.js.CreateOrUpdateConsumer(ctx, catalogEvents, jetstream.ConsumerConfig{Durable: "builder-events", AckPolicy: jetstream.AckExplicitPolicy,
FilterSubject: meshcatalog.SubjectVersionReleased, DeliverPolicy: jetstream.DeliverNewPolicy})
if err != nil {
t.Fatal(err)
}
next := func(module, version string) jetstream.Msg {
t.Helper()
data, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: module, Version: version})
if _, err := b.js.Publish(ctx, meshcatalog.SubjectVersionReleased, data); err != nil {
t.Fatal(err)
}
m, err := evs.Next(jetstream.FetchMaxWait(10 * time.Second))
if err != nil {
t.Fatal(err)
}
return m
}
if !rv.heard(ctx, next("m4", "0.2.1")) {
t.Fatal("the reservations did not take version-released")
}
if _, raised := found.vals[elsewhere]; raised || !slices.Equal(tagsWritten, []string{"modules/m4/v0.2.1@c-mine"}) {
t.Errorf("after version-released %s raised %v, tags written %v: want it cleared and modules/m4/v0.2.1 written at c-mine, no tag moved", elsewhere, raised, tagsWritten)
}
// Design 47 H2 §794 (whole, H-A-453 (3), H-A-462): a message the builder's handler leaves unacknowledged is kept on its
// consumer's ledger in the state consumers on the bus; held six minutes, the health names that backlog, and within five
// minutes it does not.
consumers, err := b.js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, process.ConsumersState)})
if err != nil {
t.Fatal(err)
}
held := time.Now()
hub := &oneHandler{}
aged := agedHub{hub: hub, ledgers: &ledgers{logf: t.Logf, now: func() time.Time { return held },
sink: consumersSink(process.AwaitBucket(ctx, b.js, nil, builds.StateBucket(builds.BuilderModule, process.ConsumersState), "", t.Logf))}}
_ = aged.Handle(meshcatalog.SubjectVersionReleased, func(m jetstream.Msg) { _ = m.Nak() }) // a handler standing still: asked again
hub.handle(next("m5", "0.1.0"))
state := versions.Reader{Keys: func() ([]string, error) {
l, err := consumers.ListKeys(ctx)
if err != nil {
return nil, err
}
var keys []string
for k := range l.Keys() {
keys = append(keys, k)
}
return keys, nil
}, Get: func(k string) (json.RawMessage, bool, error) {
e, err := consumers.Get(ctx, k)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
return e.Value(), true, nil
}}
if a := versions.BuilderHealth(state, held.Add(6*time.Minute), 5*time.Minute); a.Healthy || !strings.Contains(a.Why, "builder-events (its oldest unacknowledged message waits 6m0s") {
t.Errorf("the health with a backlog held six minutes = %+v, want unhealthy naming builder-events", a)
}
if a := versions.BuilderHealth(state, held.Add(4*time.Minute), 5*time.Minute); !a.Healthy {
t.Errorf("the health four minutes in = %+v, want healthy", a)
}
} }
@@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
"os" "os"
"sort"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@@ -59,9 +58,6 @@ type publishItems struct {
// retired are the done builds a newer reservation or release of the same module supersedes, with why (H-A-291 (1)); nil // retired are the done builds a newer reservation or release of the same module supersedes, with why (H-A-291 (1)); nil
// retires none. // retires none.
retired func(ctx context.Context, all []versions.ReservedVersion) (map[string]string, error) retired func(ctx context.Context, all []versions.ReservedVersion) (map[string]string, error)
// unheard is how many messages the builder's durable on the events stream holds pending and unacknowledged, read before each
// try (design 47 H H-A-269 (2), H-A-272); nil reads none.
unheard func(ctx context.Context) (int, error)
// judge is what the registries' own record says of a version's missing artifacts (H-A-272, H-A-274, H-A-275); nil judges none. // judge is what the registries' own record says of a version's missing artifacts (H-A-272, H-A-274, H-A-275); nil judges none.
judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error)
// markHeld marks the artifacts the registries hold with the built digest published from their record, as their published heard // markHeld marks the artifacts the registries hold with the built digest published from their record, as their published heard
@@ -387,20 +383,11 @@ func (p *publishItems) Ended(ctx context.Context, module, version string) {
} }
// notAgain says why a version's publish is not asked again now, empty when it is (design 47 H H-A-269 (2), H-A-272, H-A-274, // notAgain says why a version's publish is not asked again now, empty when it is (design 47 H H-A-269 (2), H-A-272, H-A-274,
// H-A-275): the builder's durable holds UnheardBound messages or more not yet heard, so a published of it may be among them; or the // H-A-275), judged from what the builder recorded and the registries' record, never from a count of its events unheard (design
// registries' own record holds every missing artifact at its version with its built digest, which marks them published from that // 47 H2 H-A-514 addendum): the registries' own record holds every missing artifact at its version with its built digest, which
// record; or a registry holds the version at another digest, which moves the build to the next free number (gone: this item is // marks them published from that record; or a registry holds the version at another digest, which moves the build to the next
// ended with the old number). A count or a record that cannot be read is said, and does not hold the ask. // free number (gone: this item is ended with the old number). A record that cannot be read is said, and does not hold the ask.
func (p *publishItems) notAgain(ctx context.Context, v versions.ReservedVersion) (why string, gone bool) { func (p *publishItems) notAgain(ctx context.Context, v versions.ReservedVersion) (why string, gone bool) {
if p.unheard != nil {
n, err := p.unheard(ctx)
switch {
case err != nil:
p.logf("%s %s: the builder's events consumer cannot be read, so the publish is asked again as it stands: %v", v.Module, v.Version, err)
case n >= versions.UnheardBound:
return fmt.Sprintf("the builder's events consumer holds %d messages not yet heard (the bound is %d), a published of it may be among them", n, versions.UnheardBound), false
}
}
if p.judge == nil { if p.judge == nil {
return "", false return "", false
} }
@@ -425,22 +412,6 @@ func (p *publishItems) notAgain(ctx context.Context, v versions.ReservedVersion)
return "", false return "", false
} }
// unheardVia reads the builder's durable on the events stream: its messages pending and those given and not yet acknowledged
// (design 47 H H-A-272), what it has not yet heard.
func unheardVia(js jetstream.JetStream, stream, durable string) func(context.Context) (int, error) {
return func(ctx context.Context) (int, error) {
c, err := js.Consumer(ctx, stream, durable)
if err != nil {
return 0, err
}
info, err := c.Info(ctx)
if err != nil {
return 0, err
}
return int(info.NumPending) + info.NumAckPending, nil
}
}
// registryVersionsVia asks a registry seat's verb versions for a name (H-A-272): each version it holds with its digest. // registryVersionsVia asks a registry seat's verb versions for a name (H-A-272): each version it holds with its digest.
func registryVersionsVia(call toolCaller) func(context.Context, string, string) ([]versions.HeldVersion, error) { func registryVersionsVia(call toolCaller) func(context.Context, string, string) ([]versions.HeldVersion, error) {
return func(_ context.Context, seat, name string) ([]versions.HeldVersion, error) { return func(_ context.Context, seat, name string) ([]versions.HeldVersion, error) {
@@ -531,9 +502,9 @@ func builtOf(all []versions.ReservedVersion) []versions.ReservedVersion {
// the manifest's old streams section with the work-queue retention, the module's own, consumed by the module's one process on the // the manifest's old streams section with the work-queue retention, the module's own, consumed by the module's one process on the
// module's account (H-A-464), which declares no bus and so is the stream's one reader by the module's shape; each item on // module's account (H-A-464), which declares no bus and so is the stream's one reader by the module's shape; each item on
// `mesh.stream.<module>.event.publish.<holder>.<class>.<module>.<version>` under the message id // `mesh.stream.<module>.event.publish.<holder>.<class>.<module>.<version>` under the message id
// `<holder>.<class>.<module>.<version>`. The builder makes the pull consumers at run time as it learns a holder, // `<holder>.<class>.<module>.<version>`. The builder makes one pull consumer at run time as it learns a holder,
// `publishes-<holder>-<class>`, with ack wait publish-pause-max, max ack pending four and max deliveries ten, and pulls the live // `publishes-<holder>`, with ack wait publish-pause-max, max ack pending four and max deliveries ten, and sends its items in the
// class first, at most four sends at once per holder. // order the consumer gives them, at most four at once per holder (H-A-483 and its addenda).
type publishQueue struct { type publishQueue struct {
js jetstream.JetStream js jetstream.JetStream
binding func() (publishesStream, error) binding func() (publishesStream, error)
@@ -555,16 +526,16 @@ func publishesOf(module string) func() (publishesStream, error) {
return func() (publishesStream, error) { return b, nil } return func() (publishesStream, error) { return b, nil }
} }
// The consumers' numbers (H-A-446 (2)): at most four sends in flight per holder and class, and ten deliveries, the work queue's // The consumer's numbers (H-A-446 (2)): at most four sends in flight per holder, and ten deliveries, the work queue's largest;
// largest; the builder ends an item at publish-tries anyway. // the builder ends an item at publish-tries anyway.
const ( const (
publishesMaxAckPending = versions.PublishSendsAtOnce publishesMaxAckPending = versions.PublishSendsAtOnce
publishesMaxDeliver = 10 publishesMaxDeliver = 10
) )
// publishesConsumer is the durable consumer of holder's items of class. // publishesConsumer is the one durable consumer of holder's items (H-A-483 addendum).
func publishesConsumer(holder, class string) string { func publishesConsumer(holder string) string {
return versions.PublishesLocal + "-" + holder + "-" + class return versions.PublishesLocal + "-" + holder
} }
// subject is the item's subject on the bus. // subject is the item's subject on the bus.
@@ -616,8 +587,15 @@ func (pq *publishQueue) learnAll(ctx context.Context) error {
return nil return nil
} }
// learn starts holder's pull once. // learn starts holder's pull once. A holder is a module name, so one ending in -live or -again, the class durables an earlier
// release made, is refused, said (H-A-483, third addendum): its consumer would be another holder's old durable.
func (pq *publishQueue) learn(ctx context.Context, holder string) { func (pq *publishQueue) learn(ctx context.Context, holder string) {
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
if strings.HasSuffix(holder, "-"+class) {
pq.logf("the publishes of %s are refused: a holder is a module name, and one ending in -%s names the class durable of an earlier release (H-A-483)", holder, class)
return
}
}
pq.mu.Lock() pq.mu.Lock()
if pq.pulling == nil { if pq.pulling == nil {
pq.pulling = map[string]bool{} pq.pulling = map[string]bool{}
@@ -636,94 +614,71 @@ func (pq *publishQueue) learn(ctx context.Context, holder string) {
} }
} }
// pull makes holder's two consumers and dispatches their items, the live class first, at most four sends at once: an again item // pull makes holder's one consumer and dispatches its items (design 47 H2 §793, H-A-483 and its addenda): first it retires the
// waits while a live one waits on the queue. // holder's class durables an earlier release made (`-live`, `-again`), whose filters a work queue refuses beside the one; their
// unacknowledged items stay on the queue and reach the one consumer.
func (pq *publishQueue) pull(ctx context.Context, holder string) error { func (pq *publishQueue) pull(ctx context.Context, holder string) error {
b, err := pq.binding() b, err := pq.binding()
if err != nil { if err != nil {
return err return err
} }
chans := map[string]chan jetstream.Msg{} for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
var live jetstream.Consumer old := publishesConsumer(holder) + "-" + class
for _, class := range []string{versions.PublishClassStart, versions.PublishClassLive} { // the again first: the live is first by the dispatch, not by luck err := pq.js.DeleteConsumer(ctx, b.Stream, old)
c, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder, class), switch {
FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy, case err == nil:
AckWait: pq.ackWait, MaxAckPending: publishesMaxAckPending, MaxDeliver: publishesMaxDeliver}) pq.logf("the consumer %s of an earlier release is removed: the publishes of %s have one consumer (H-A-483)", old, holder)
if err != nil { case !errors.Is(err, jetstream.ErrConsumerNotFound):
return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder, class), err) return fmt.Errorf("the consumer %s of an earlier release is not removed: %w", old, err)
}
ch := make(chan jetstream.Msg, publishesMaxAckPending)
cc, err := c.Consume(func(m jetstream.Msg) { ch <- m }, jetstream.PullMaxMessages(publishesMaxAckPending))
if err != nil {
return fmt.Errorf("the consumer %s is not pulled: %w", publishesConsumer(holder, class), err)
}
go func() { <-ctx.Done(); cc.Stop() }()
chans[class] = ch
if class == versions.PublishClassLive {
live = c
} }
} }
liveWaits := func() bool { c, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder),
info, err := live.Info(ctx) FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + ".>", AckPolicy: jetstream.AckExplicitPolicy,
return err == nil && info.NumPending > 0 AckWait: pq.ackWait, MaxAckPending: publishesMaxAckPending, MaxDeliver: publishesMaxDeliver})
if err != nil {
return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder), err)
} }
pq.logf("pulling the publishes of %s, the live first", holder) pq.logf("pulling the publishes of %s", holder)
go pq.dispatch(ctx, chans[versions.PublishClassLive], chans[versions.PublishClassStart], liveWaits) go pq.dispatch(ctx, holder, c)
return nil return nil
} }
// dispatch runs the items of one holder, at most four at once, every live item before an again one: an again item pulled while // dispatch runs the items of one holder in the order its one consumer gives them, at most four at once (design 47 H2 §793,
// a live one waits on the queue (liveWaits) runs after it. // H-A-483): each free slot takes the next item through a pull that waits, so an item put or handed back after its pause is
func (pq *publishQueue) dispatch(ctx context.Context, live, again <-chan jetstream.Msg, liveWaits func() bool) { // received the moment the bus gives it; an item handed back reappears only after its pause, so an item put meanwhile goes
// before it. A pull the bus refuses ends the dispatch, said; the holder is pulled again when an item of it is put.
func (pq *publishQueue) dispatch(ctx context.Context, holder string, c jetstream.Consumer) {
sem := make(chan struct{}, versions.PublishSendsAtOnce) sem := make(chan struct{}, versions.PublishSendsAtOnce)
run := func(m jetstream.Msg) {
go func() {
defer func() { <-sem }()
pq.take(ctx, m)
}()
}
var spare jetstream.Msg // an again item pulled while a live one waited
for { for {
select { select {
case sem <- struct{}{}: case sem <- struct{}{}:
case <-ctx.Done(): case <-ctx.Done():
return return
} }
select { var got jetstream.Msg
case m := <-live: b, err := c.Fetch(1)
run(m) if err == nil {
continue for m := range b.Messages() {
default: got = m
}
m := spare
spare = nil
if m == nil {
select {
case lm := <-live:
run(lm)
continue
case m = <-again:
case <-ctx.Done():
return
} }
err = b.Error()
} }
if liveWaits() { if err != nil && !errors.Is(err, jetstream.ErrNoMessages) && !errors.Is(err, nats.ErrTimeout) && ctx.Err() == nil {
spare = m <-sem
select { pq.logf("the publishes of %s are not pulled: %v; they are pulled when an item of it is put", holder, err)
case lm := <-live: pq.mu.Lock()
run(lm) delete(pq.pulling, holder)
case <-ctx.Done(): pq.mu.Unlock()
return return
} }
if got == nil {
<-sem
continue continue
} }
select { go func(m jetstream.Msg) {
case lm := <-live: // came while the queue was asked defer func() { <-sem }()
spare = m pq.take(ctx, m)
run(lm) }(got)
default:
run(m)
}
} }
} }
@@ -827,45 +782,6 @@ func (pq *publishQueue) drop(ctx context.Context, items *publishItems, module, v
return fmt.Sprintf("the publish of %s %s is dropped: %d items terminated, and none is sent or put again", module, version, len(qs)), nil return fmt.Sprintf("the publish of %s %s is dropped: %d items terminated, and none is sent or put again", module, version, len(qs)), nil
} }
// first is builder_publish_first (§793): each again item of the version is put again as live, under the message id
// `<holder>.live.<module>.<version>`, and the old terminated; a live id the queue holds within its window takes nothing, and the
// old stays, said.
func (pq *publishQueue) first(ctx context.Context, items *publishItems, module, version string) (string, error) {
qs, st, err := pq.itemsOf(ctx, module, version, versions.PublishClassStart)
if err != nil {
return "", fmt.Errorf("the work queue %s cannot be read: %w", versions.PublishesLocal, err)
}
if len(qs) == 0 {
return "", fmt.Errorf("the work queue %s holds no again item of %s %s", versions.PublishesLocal, module, version)
}
var moved, kept []string
for subj, q := range qs {
q.Class = versions.PublishClassLive
dup, err := pq.put(ctx, q)
if err != nil {
return "", fmt.Errorf("%s %s is not put again as live at %s: %w", module, version, q.Holder, err)
}
if dup {
kept = append(kept, q.Holder)
continue
}
if err := st.Purge(ctx, jetstream.WithPurgeSubject(subj)); err != nil {
return "", fmt.Errorf("the again item of %s %s at %s is not terminated: %w", module, version, q.Holder, err)
}
moved = append(moved, q.Holder)
}
for _, h := range items.settle(module, version, func(h heldItem) bool { return h.q.Class == versions.PublishClassStart }) {
_ = h.m.Term()
}
sort.Strings(moved)
answer := fmt.Sprintf("%s %s is put first as live at %s, its again item terminated", module, version, strings.Join(moved, ", "))
if len(kept) > 0 {
sort.Strings(kept)
answer += fmt.Sprintf("; at %s the work queue holds its live id within the duplicates window, so its again item stays", strings.Join(kept, ", "))
}
return answer, nil
}
// endItem writes the version's publish item ended with answer, made when none stands: Try and take then leave it, and a start // endItem writes the version's publish item ended with answer, made when none stands: Try and take then leave it, and a start
// asks it no more. // asks it no more.
func (p *publishItems) endItem(ctx context.Context, module, version, answer string) error { func (p *publishItems) endItem(ctx context.Context, module, version, answer string) error {
@@ -284,8 +284,7 @@ func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T)
call := func(string, any) (json.RawMessage, error) { call := func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
} }
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf) rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf)
rv.filled.Store(true)
tried := make(chan string, 4) tried := make(chan string, 4)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: time.Now, logf: t.Logf, items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: time.Now, logf: t.Logf,
reserved: func(ctx context.Context, m, v string) (versions.ReservedVersion, bool, error) { reserved: func(ctx context.Context, m, v string) (versions.ReservedVersion, bool, error) {
@@ -361,12 +360,12 @@ func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T)
} }
} }
// TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard: design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275 — a try asks the // Design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275, and design 47 H2 H-A-514 addendum: a publish is asked again judged from
// publish again only while the builder's durable holds fewer than a hundred messages not yet heard and the registries' record lacks // what the builder recorded and the registries' record alone, never from how many events its consumer holds unheard: a
// an artifact; a record holding every missing artifact with the built digest marks them published from it; a record holding the // reservation marking every artifact published is acknowledged; a record holding every missing artifact with the built digest
// version at another digest moves the build to the next free number and ends this item; a skipped try spends no try and is written // marks them published from it; a record holding the version at another digest moves the build to the next free number and
// again with its pause; a count that cannot be read holds no ask. // ends this item; a record lacking it is asked again; a skipped try spends no try and is written again with its pause.
func TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard(t *testing.T) { func TestAPublishIsAskedAgainFromWhatTheBuilderRecorded(t *testing.T) {
ctx := context.Background() ctx := context.Background()
now := time.Date(2026, 11, 21, 15, 21, 0, 0, time.UTC) now := time.Date(2026, 11, 21, 15, 21, 0, 0, time.UTC)
v := versions.ReservedVersion{Module: "node-tools", Version: "0.1.37", Artifacts: map[string]string{"node-tools:program": "sha256:7c9b10"}, BuiltAt: now} v := versions.ReservedVersion{Module: "node-tools", Version: "0.1.37", Artifacts: map[string]string{"node-tools:program": "sha256:7c9b10"}, BuiltAt: now}
@@ -375,28 +374,31 @@ func TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard(t *testing.T) {
other.Digest = "sha256:83bec1" other.Digest = "sha256:83bec1"
for _, c := range []struct { for _, c := range []struct {
name string name string
unheard int published bool
countErr error
judged versions.Judged judged versions.Judged
wantAsked, wantMark, wantMov bool wantAsked, wantMark, wantMov bool
}{ }{
{name: "thousands behind: no ask, the registry not read", unheard: 2944}, {name: "its reservation marks it published: acknowledged, no ask", published: true},
{name: "at the bound: no ask", unheard: versions.UnheardBound}, {name: "the registry holds it: marked from its record, no ask", judged: versions.Judged{All: true, Held: []versions.HeldArtifact{at}}, wantMark: true},
{name: "heard up, the registry holds it: marked from its record, no ask", unheard: versions.UnheardBound - 1, judged: versions.Judged{All: true, Held: []versions.HeldArtifact{at}}, wantMark: true}, {name: "the registry holds the number at another digest: moved, no ask", judged: versions.Judged{Elsewhere: []versions.HeldArtifact{other}}, wantMov: true},
{name: "the registry holds the number at another digest: moved, no ask", unheard: 3, judged: versions.Judged{Elsewhere: []versions.HeldArtifact{other}}, wantMov: true}, {name: "the registry lacks it: asked, whatever the events consumer holds", judged: versions.Judged{Lacks: "none"}, wantAsked: true},
{name: "heard up, the registry lacks it: asked", unheard: 3, judged: versions.Judged{Lacks: "none"}, wantAsked: true},
{name: "the count unreadable, the registry lacks it: asked", countErr: errors.New("no consumer"), judged: versions.Judged{Lacks: "none"}, wantAsked: true},
} { } {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
asked, judged, marked, moved := 0, 0, 0, 0 asked, judged, marked, moved := 0, 0, 0, 0
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: func() time.Time { return now }, logf: t.Logf, p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: func() time.Time { return now }, logf: t.Logf,
reserved: func(context.Context, string, string) (versions.ReservedVersion, bool, error) { return v, true, nil }, reserved: func(context.Context, string, string) (versions.ReservedVersion, bool, error) {
if c.published {
w := v
w.Published = map[string]bool{"node-tools:program": true}
return w, true, nil
}
return v, true, nil
},
send: func(context.Context, versions.QueuedPublish) versions.SendFate { send: func(context.Context, versions.QueuedPublish) versions.SendFate {
asked++ asked++
return versions.SendFate{Sent: true} return versions.SendFate{Sent: true}
}, },
unheard: func(context.Context) (int, error) { return c.unheard, c.countErr },
judge: func(context.Context, versions.ReservedVersion) (versions.Judged, error) { judge: func(context.Context, versions.ReservedVersion) (versions.Judged, error) {
judged++ judged++
return c.judged, nil return c.judged, nil
@@ -421,6 +423,12 @@ func TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard(t *testing.T) {
if (asked == 1) != c.wantAsked || (marked == 1) != c.wantMark || (moved == 1) != c.wantMov { if (asked == 1) != c.wantAsked || (marked == 1) != c.wantMark || (moved == 1) != c.wantMov {
t.Fatalf("asked %d, marked %d, moved %d; want asked %v, marked %v, moved %v", asked, marked, moved, c.wantAsked, c.wantMark, c.wantMov) t.Fatalf("asked %d, marked %d, moved %d; want asked %v, marked %v, moved %v", asked, marked, moved, c.wantAsked, c.wantMark, c.wantMov)
} }
if c.published {
if fmt.Sprint(m.settled) != "[ack]" || judged != 0 {
t.Errorf("a version its reservation marks published settled %v, the registry read %d times; want acknowledged, none read", m.settled, judged)
}
return
}
if c.wantMov { if c.wantMov {
if _, ok := kv.vals[key]; ok || fmt.Sprint(m.settled) != "[term]" { if _, ok := kv.vals[key]; ok || fmt.Sprint(m.settled) != "[term]" {
t.Errorf("the moved version's old item is written again, or its item settled %v, not terminated", m.settled) t.Errorf("the moved version's old item is written again, or its item settled %v, not terminated", m.settled)
@@ -434,9 +442,20 @@ func TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard(t *testing.T) {
if !c.wantAsked && fmt.Sprint(m.settled) != "[nak 30s]" { if !c.wantAsked && fmt.Sprint(m.settled) != "[nak 30s]" {
t.Errorf("an item not sent was settled %v, want it handed back with the pause and no try spent", m.settled) t.Errorf("an item not sent was settled %v, want it handed back with the pause and no try spent", m.settled)
} }
if c.unheard >= versions.UnheardBound && judged != 0 {
t.Error("the registry is read while a published may be unheard")
}
}) })
} }
} }
// Design 47 H2 H-A-483 (third addendum): a holder is a module name, so one ending in -live or -again, the class durables of an
// earlier release, is refused at the learn, said, and nothing of it is pulled.
func TestAHolderNamedLikeAClassDurableIsRefused(t *testing.T) {
for _, holder := range []string{"oci-live", "oci-again"} {
var said []string
pq := &publishQueue{logf: func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) },
binding: func() (publishesStream, error) { return publishesStream{}, errors.New("no bus in a unit test") }}
pq.learn(context.Background(), holder)
if len(said) != 1 || !strings.Contains(said[0], "the publishes of "+holder+" are refused") || pq.pulling[holder] {
t.Errorf("%s: said %q, pulling %v, want it refused at the learn, said once, nothing pulled", holder, said, pq.pulling[holder])
}
}
}
@@ -65,7 +65,7 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi
released(ctx, b, kv, e, r, logf) released(ctx, b, kv, e, r, logf)
return return
} }
if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModePublishFirst || r.Mode == build.ModeFloorAgain || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone { if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone {
// A version's hand act (design 51 *Tools of the builder*) may build again, so it is answered beside the watch. // A version's hand act (design 51 *Tools of the builder*) may build again, so it is answered beside the watch.
go versionActed(ctx, acts, kv, e, r, logf) go versionActed(ctx, acts, kv, e, r, logf)
return return
@@ -196,7 +196,7 @@ func emitBuildEnded(ctx context.Context, js jetstream.JetStream, cred process.Ac
return nil return nil
} }
// versionActed answers a reasks value of builder_publish_again, builder_floor_again or builder_old_form's drop, a hand act said in the log. // versionActed answers a reasks value of builder_publish_again, builder_publish_drop, builder_reserve_done, builder_reserved_drop or builder_old_form's drop, a hand act said in the log.
func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk, logf func(string, ...any)) { func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk, logf func(string, ...any)) {
var err error var err error
if r.Mode == build.ModeRepublish { if r.Mode == build.ModeRepublish {
@@ -208,11 +208,8 @@ func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue
r.Answer = "queued " + fmt.Sprint(len(r.Queued)) + " versions to publish again: " + strings.Join(r.Queued, ", ") + "; builder_publish_queue shows them" r.Answer = "queued " + fmt.Sprint(len(r.Queued)) + " versions to publish again: " + strings.Join(r.Queued, ", ") + "; builder_publish_queue shows them"
} }
} }
} else if r.Mode == build.ModePublishDrop || r.Mode == build.ModePublishFirst { } else if r.Mode == build.ModePublishDrop {
act := acts.PublishDrop act := acts.PublishDrop
if r.Mode == build.ModePublishFirst {
act = acts.PublishFirst
}
if act == nil { if act == nil {
err = errors.New("this builder keeps no work queue of publishes") err = errors.New("this builder keeps no work queue of publishes")
} else { } else {
@@ -230,14 +227,10 @@ func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue
} else { } else {
r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.By, r.Why, r.At) r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.By, r.Why, r.At)
} }
} else if r.Mode == build.ModeOldFormDrop { } else if acts.DropOldForm == nil {
if acts.DropOldForm == nil { err = errors.New("this builder keeps no old-form window")
err = errors.New("this builder keeps no old-form window")
} else {
r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
}
} else { } else {
r.Answer, err = acts.FloorAgain(ctx, r.Name) r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
} }
if err != nil { if err != nil {
r.Answer, r.Refused = err.Error(), true r.Answer, r.Refused = err.Error(), true
@@ -42,7 +42,7 @@ import (
// its grant. The gate over the seat's assignments, and its refusal, are mesh-sdk's (buildrun.PlacedNodes, // its grant. The gate over the seat's assignments, and its refusal, are mesh-sdk's (buildrun.PlacedNodes,
// issue 774). // issue 774).
func TestARefusedBucketIsSaidAndThePartGoesOn(t *testing.T) { func TestARefusedBucketIsSaidAndThePartGoesOn(t *testing.T) {
t.Run("a floor's wake is heard on the events consumer (design 51 The floor)", aFloorsWakeIsHeard) t.Run("a registry seat's outcome is heard on the events consumer (DLV-B4)", aSeatsOutcomeIsHeard)
t.Run("a failed trunk build is a finding until a later done one (DLV-B7)", aFailedTrunkBuildIsAFinding) t.Run("a failed trunk build is a finding until a later done one (DLV-B7)", aFailedTrunkBuildIsAFinding)
refused := refusingBus{err: errors.New("nats: permissions violation for publish to $JS.API.CONSUMER.CREATE.KV_mesh-delivery-indexer_modules")} refused := refusingBus{err: errors.New("nats: permissions violation for publish to $JS.API.CONSUMER.CREATE.KV_mesh-delivery-indexer_modules")}
if _, err := process.EssentialBucket(context.Background(), refusingBus{refuseOpen: true, err: refused.err}, "builder", "mesh-delivery-indexer_modules", "work"); err == nil || if _, err := process.EssentialBucket(context.Background(), refusingBus{refuseOpen: true, err: refused.err}, "builder", "mesh-delivery-indexer_modules", "work"); err == nil ||
@@ -250,33 +250,16 @@ func (m *wakeMsg) Headers() nats.Header {
return nil return nil
} }
func aFloorsWakeIsHeard(t *testing.T) { func aSeatsOutcomeIsHeard(t *testing.T) {
var logs bytes.Buffer var logs bytes.Buffer
holders := map[string]string{"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer"} // DLV-B4: a registry seat's outcome on the events consumer moves a version; a by-digest publish marks none and is taken.
waits := &versions.FloorWaits{Holder: func(seat string) (string, bool) { h, ok := holders[seat]; return h, ok }} h := &seatHearer{b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
waits.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceRequirements}}, nil, time.Unix(0, 0))
waits.Wait("m/img", versions.SeatImages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0))
f := &floorWake{b: &build.Builder{}, waits: waits, logf: log.New(&logs, "", 0).Printf}
accepted := &wakeMsg{subject: takenInSubject}
if !f.heard(context.Background(), accepted) || !accepted.acked || !strings.Contains(logs.String(), "the floor of m/lib is asked again: take-in.taken") {
t.Fatalf("take-in.taken: acked %v, log %q", accepted.acked, logs.String())
}
logs.Reset()
cleared := &wakeMsg{subject: conditionClearedSubject, data: []byte(`{"subject":{"scope":"probe","id":"ace/mesh-delivery-forge-bridge"}}`)}
if !f.heard(context.Background(), cleared) || !strings.Contains(logs.String(), "the floor of m/img is asked again: condition-cleared") {
t.Fatalf("condition-cleared: log %q", logs.String())
}
if f.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
t.Fatal("artifacts-gone was taken as a floor's wake")
}
// DLV-B4: a registry seat's outcome on the same consumer moves a version; a published wakes a name whose seat was
// silent; one the state cannot take is left for the bus to give again.
logs.Reset()
waits.Wait("m/pkg", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceSeat}}, nil, time.Unix(0, 0))
h := &seatHearer{n: &versions.Numberer{Versions: versions.Versions{Store: noVersions{}}, Waits: waits}, b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
byDigest := &wakeMsg{subject: "mesh.seat.go-package-registry.event.published", data: []byte(`{"name":"m/other","digest":"sha256:aa","kind":"package","holder":"gitea"}`)} byDigest := &wakeMsg{subject: "mesh.seat.go-package-registry.event.published", data: []byte(`{"name":"m/other","digest":"sha256:aa","kind":"package","holder":"gitea"}`)}
if !h.heard(context.Background(), byDigest) || !byDigest.acked || !strings.Contains(logs.String(), "the floor of m/pkg is asked again: go-package-registry said published") { if !h.heard(context.Background(), byDigest) || !byDigest.acked || byDigest.naked {
t.Fatalf("published: acked %v, log %q", byDigest.acked, logs.String()) t.Fatalf("published: acked %v, naked %v, log %q", byDigest.acked, byDigest.naked, logs.String())
}
if h.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
t.Fatal("artifacts-gone was taken as a seat's outcome")
} }
// Design 47 G §369, A-415: a published of a version the reservation numbered, which the state versions does not hold, is // Design 47 G §369, A-415: a published of a version the reservation numbered, which the state versions does not hold, is
// taken: its artifact is marked and package-published said, never left for the bus to give again. // taken: its artifact is marked and package-published said, never left for the bus to give again.
@@ -284,9 +267,8 @@ func aFloorsWakeIsHeard(t *testing.T) {
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, func(string, any) (json.RawMessage, error) { rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, }, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil, t.Logf) &findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, t.Logf)
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { saidPub = append(saidPub, p); return nil } rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { saidPub = append(saidPub, p); return nil }
rv.filled.Store(true)
res, err := rv.Reserve(context.Background(), "m", "0.1", []string{"m:program"}, versions.Source{}) res, err := rv.Reserve(context.Background(), "m", "0.1", []string{"m:program"}, versions.Source{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -299,9 +281,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
if !h.heard(context.Background(), published) || !published.acked || published.naked || len(saidPub) != 1 || saidPub[0].Artifact != "m:program" { if !h.heard(context.Background(), published) || !published.acked || published.naked || len(saidPub) != 1 || saidPub[0].Artifact != "m:program" {
t.Fatalf("a published of a reserved version: acked %v, naked %v, said %+v, log %q", published.acked, published.naked, saidPub, logs.String()) t.Fatalf("a published of a reserved version: acked %v, naked %v, said %+v, log %q", published.acked, published.naked, saidPub, logs.String())
} }
if h.heard(context.Background(), &wakeMsg{subject: takenInSubject}) {
t.Fatal("take-in.taken was taken as a seat's outcome")
}
// Design 47 G A-420: a message left for the bus is said given up on the last delivery its consumer allows, never before. // Design 47 G A-420: a message left for the bus is said given up on the last delivery its consumer allows, never before.
for _, n := range []uint64{4, EventDeliveries} { for _, n := range []uint64{4, EventDeliveries} {
logs.Reset() logs.Reset()
@@ -313,27 +292,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
} }
} }
// noVersions is a state versions that holds nothing.
type noVersions struct{}
func (noVersions) Get(context.Context, string) ([]byte, uint64, bool, error) {
return nil, 0, false, nil
}
func (noVersions) Create(context.Context, string, []byte) (uint64, error) {
return 0, errors.New("read only")
}
func (noVersions) Update(context.Context, string, []byte, uint64) (uint64, error) {
return 0, errors.New("read only")
}
func (noVersions) KeysOf(context.Context, string) ([]string, error) { return nil, nil }
// failingVersions is a state versions that cannot be read.
type failingVersions struct{ noVersions }
func (failingVersions) KeysOf(context.Context, string) ([]string, error) {
return nil, errors.New("down")
}
func aFailedTrunkBuildIsAFinding(t *testing.T) { func aFailedTrunkBuildIsAFinding(t *testing.T) {
st := &memFindings{vals: map[string][]byte{}} st := &memFindings{vals: map[string][]byte{}}
f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }} f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
@@ -354,30 +312,11 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
if _, ok := st.vals[key]; ok { if _, ok := st.vals[key]; ok {
t.Error("a later done trunk build leaves build-failed") t.Error("a later done trunk build leaves build-failed")
} }
// The floor finding: raised while a name waits on its floor, cleared once it is known. // Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a seat's outcome
fw := &versions.FloorWaits{Said: f.floorSaid(context.Background())} // that does not read seat-outcome-unread; a later published of the name clears the first, the seat's next outcome that
fw.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0)) // reads the second. The numbered version's bound goes with the numbering from before G (design 47 H §756).
floorKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/lib", versions.FloorSilent) pubs := &publishes{findings: f}
if got, err := decodeFinding(st.vals[floorKey]); err != nil || !strings.Contains(got.Summary, "git.tags did not answer") { h := &seatHearer{b: &build.Builder{}, logf: t.Logf, pub: pubs}
t.Fatalf("the floor finding = %+v, %v", got, err)
}
fw.Answered("m/lib")
if _, ok := st.vals[floorKey]; ok {
t.Error("a known floor leaves floor-silent")
}
// Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a version
// no holder answered within its bound publish-unanswered, a seat's outcome that does not read seat-outcome-unread;
// a later published of the name clears the first two, the seat's next outcome that reads the third.
vs := versions.Versions{Store: memVersions{}}
for _, v := range []string{"0.1.3", "0.1.4"} {
raw, err := versions.Encode(versions.Entry{Name: "m/program", Kind: versions.KindBundle, Series: "0.1", Version: v, Seat: "oci-artifact-registry", State: versions.Numbered})
if err != nil {
t.Fatal(err)
}
vs.Store.(memVersions)[versions.Key("m/program", v)] = raw
}
pubs := &publishes{bounds: func() jetstream.KeyValue { return nil }, versions: vs, findings: f, bound: versions.PublishBound, logf: t.Logf}
h := &seatHearer{n: &versions.Numberer{Versions: vs}, b: &build.Builder{}, logf: t.Logf, pub: pubs}
refusedKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishRefused) refusedKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishRefused)
refused := &wakeMsg{subject: "mesh.seat.oci-artifact-registry.event.refused", data: []byte(`{"name":"m/program","version":"0.1.3","digest":"sha256:bb","reason":"bytes differ"}`)} refused := &wakeMsg{subject: "mesh.seat.oci-artifact-registry.event.refused", data: []byte(`{"name":"m/program","version":"0.1.3","digest":"sha256:bb","reason":"bytes differ"}`)}
if !h.heard(context.Background(), refused) || !refused.acked { if !h.heard(context.Background(), refused) || !refused.acked {
@@ -386,18 +325,10 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
if got, err := decodeFinding(st.vals[refusedKey]); err != nil || !strings.Contains(got.Summary, "refused to publish m/program@0.1.3") || !strings.Contains(got.Summary, "bytes differ") { if got, err := decodeFinding(st.vals[refusedKey]); err != nil || !strings.Contains(got.Summary, "refused to publish m/program@0.1.3") || !strings.Contains(got.Summary, "bytes differ") {
t.Fatalf("a holder's refused: the finding = %+v, %v", got, err) t.Fatalf("a holder's refused: the finding = %+v, %v", got, err)
} }
pubs.ended(context.Background(), purged{key: versions.PublishBoundKey("m/program", "0.1.4")}) // A publish-unanswered a builder of before the change raised is cleared by the name's next published.
unansweredKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishUnanswered) unansweredKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishUnanswered)
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "neither published nor refused of m/program@0.1.4") { st.vals[unansweredKey] = st.vals[refusedKey]
t.Fatalf("a bound ended unanswered: the finding = %+v, %v", got, err) // A watch of bounds that cannot start is family-not-heard naming the state (review round 2).
}
// Review round 2: a bound that cannot be written is publish-unanswered at once; a watch of bounds that cannot start
// is family-not-heard naming the state.
delete(st.vals, unansweredKey)
pubs.arm(context.Background(), versions.Entry{Name: "m/program", Version: "0.1.4", Seat: "oci-artifact-registry"})
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "its bound could not be written") {
t.Fatalf("a bound not written: the finding = %+v, %v", got, err)
}
watchBounds(context.Background(), refusedWatch{err: errors.New("permissions violation")}, func(jetstream.KeyValueEntry) {}, f.notHeard(context.Background()), nil, t.Logf) watchBounds(context.Background(), refusedWatch{err: errors.New("permissions violation")}, func(jetstream.KeyValueEntry) {}, f.notHeard(context.Background()), nil, t.Logf)
if got, err := decodeFinding(st.vals[heard.Key(builds.BuilderModule, versions.BoundsState)]); err != nil || !strings.Contains(got.Summary, "permissions violation") { if got, err := decodeFinding(st.vals[heard.Key(builds.BuilderModule, versions.BoundsState)]); err != nil || !strings.Contains(got.Summary, "permissions violation") {
t.Fatalf("bounds not watched: the finding = %+v, %v", got, err) t.Fatalf("bounds not watched: the finding = %+v, %v", got, err)
@@ -603,6 +534,17 @@ func (m *memFindings) Write(_ context.Context, f mcseat.Finding) error {
return err return err
} }
// Held answers the findings kept, as the held writer answers those it holds.
func (m *memFindings) Held() []mcseat.Finding {
var out []mcseat.Finding
for _, v := range m.vals {
if f, err := decodeFinding(v); err == nil {
out = append(out, f)
}
}
return out
}
// Clear deletes the finding of scope, id and kind. // Clear deletes the finding of scope, id and kind.
func (m *memFindings) Clear(_ context.Context, scope, id, kind, _ string) error { func (m *memFindings) Clear(_ context.Context, scope, id, kind, _ string) error {
delete(m.vals, views.FindingKey(scope, id, kind)) delete(m.vals, views.FindingKey(scope, id, kind))
@@ -8,13 +8,11 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"slices" "slices"
"strings" "strings"
"sync/atomic"
"time" "time"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/process"
@@ -23,10 +21,10 @@ import (
) )
// The reservations (design 47 G §369): the builder's state reserved, the catalog's versions it numbers from, and the // The reservations (design 47 G §369): the builder's state reserved, the catalog's versions it numbers from, and the
// catalog's version-released and versions-filled it hears. // catalog's version-released it hears.
// awaitedReserved is the state reserved as versions.ReserveStore: bound once the bus holds it. // awaitedReserved is the state reserved as versions.ReserveStore: bound once the bus holds it.
type awaitedReserved struct{ awaitedVersions } type awaitedReserved struct{ awaitedState }
func (s awaitedReserved) Delete(ctx context.Context, key string) error { func (s awaitedReserved) Delete(ctx context.Context, key string) error {
kv, err := s.kv() kv, err := s.kv()
@@ -49,16 +47,15 @@ type reservations struct {
// ended ends the publish item of a build withdrawn, superseded or dropped, its held items terminated; heard acknowledges the // ended ends the publish item of a build withdrawn, superseded or dropped, its held items terminated; heard acknowledges the
// held items of a version a published newly marked (design 47 H2 §793). Nil are none. // held items of a version a published newly marked (design 47 H2 §793). Nil are none.
itemEnded, itemHeard func(ctx context.Context, module, version string) itemEnded, itemHeard func(ctx context.Context, module, version string)
filled atomic.Bool
bounds func() jetstream.KeyValue bounds func() jetstream.KeyValue
found *findings found *findings
bound time.Duration bound time.Duration
wake func(context.Context)
logf func(string, ...any) logf func(string, ...any)
// withdraw ends the running build of a module's fingerprint, superseded, with why (H-A-225); nil ends none. // withdraw ends the running build of a module's fingerprint, superseded, with why (H-A-225); nil ends none.
withdraw func(module, fingerprint, why string) withdraw func(module, fingerprint, why string)
// call asks a seat's verb: the git seat's tag (design 47 G §370). // recordAgain records the digests of a done build of module at fp its end did not record, saying so (design 47 H2 H-A-492);
call toolCaller // nil records none.
recordAgain func(ctx context.Context, module, fp, when string) (string, error)
// rebuild builds a done key of module at fp again (the build-again path, A-490; H-A-279); nil builds none. // rebuild builds a done key of module at fp again (the build-again path, A-490; H-A-279); nil builds none.
rebuild func(ctx context.Context, module, fp, why string) error rebuild func(ctx context.Context, module, fp, why string) error
// say says package-published on the seat mesh-builds; nil says none. // say says package-published on the seat mesh-builds; nil says none.
@@ -116,9 +113,9 @@ func sayReservedOn(js jetstream.JetStream, cred process.Account) func(context.Co
// newReservations makes the reserving over store; the released versions of a module are asked of the seat mesh-catalog's // newReservations makes the reserving over store; the released versions of a module are asked of the seat mesh-catalog's
// verb versions through call (design 47 G §348), the only source numbering reads them from. // verb versions through call (design 47 G §348), the only source numbering reads them from.
func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, wake func(context.Context), logf func(string, ...any)) *reservations { func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, logf func(string, ...any)) *reservations {
rv := &reservations{call: call, bounds: bounds, found: found, bound: versions.UnreleasedBound, wake: wake, logf: logf} rv := &reservations{bounds: bounds, found: found, bound: versions.UnreleasedBound, logf: logf}
rv.r = &versions.Reserver{Store: store, Filled: rv.filled.Load, ReleasedOf: func(_ context.Context, module string) ([]string, error) { rv.r = &versions.Reserver{Store: store, ReleasedOf: func(_ context.Context, module string) ([]string, error) {
raw, err := call("seat:"+meshcatalog.Seat+".versions", meshcatalog.VersionsInput{Module: module}) raw, err := call("seat:"+meshcatalog.Seat+".versions", meshcatalog.VersionsInput{Module: module})
if err != nil { if err != nil {
return nil, err return nil, err
@@ -134,8 +131,6 @@ func newReservations(store versions.ReserveStore, call toolCaller, bounds func()
return out, nil return out, nil
}} }}
rv.r.Took, rv.r.Logf, rv.r.Reserved = rv.took, logf, rv.reservedSaid rv.r.Took, rv.r.Logf, rv.r.Reserved = rv.took, logf, rv.reservedSaid
// A module's tags are read before it reserves, and a number tagged at another commit skipped (design 47 H2 §796).
rv.r.Tags, rv.r.TaggedElsewhere = tagsVia(call), rv.taggedElsewhere
return rv return rv
} }
@@ -191,62 +186,113 @@ func (rv *reservations) TakenOver(ctx context.Context, module, fingerprint strin
return rv.r.TakenOver(ctx, module, fingerprint) return rv.r.TakenOver(ctx, module, fingerprint)
} }
func (rv *reservations) Filled() bool { return rv.filled.Load() } // VersionAt is the version module's artifact is published at from the source revision of branch (H-A-547 (3), H-A-551).
func (rv *reservations) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) {
return rv.r.VersionAt(ctx, module, artifact, branch, source)
}
func (rv *reservations) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) { func (rv *reservations) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) {
return rv.r.Reserve(ctx, module, series, artifacts, src) return rv.r.Reserve(ctx, module, series, artifacts, src)
} }
// Built records the digests; once every artifact has one, the publish's bound starts (a key of the state bounds with its // Built records the digests, in one compare-and-set of the reservation (issue 1984 note 8, 1984/AC4), and then takes the
// own time to live): its end with the reservation standing is version-unreleased. // reservation's state in, whatever ended its build: this record or one before it whose end was lost, as a look hands a recorded
// reservation here with its digests (1984/AC5). A built reservation has the published kept on it taken in first, and then, on the
// reservation as that take-in left it, its publish's bound armed and its publish item asked (design 47 G A-457a; it stands until
// its release, A-456b).
func (rv *reservations) Built(ctx context.Context, module, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) error { func (rv *reservations) Built(ctx context.Context, module, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) error {
for ref, d := range digests { cur, standing, err := rv.r.Built(ctx, module, version, digests, deps)
if _, err := rv.r.Built(ctx, module, version, ref, d, deps[ref]); err != nil { if err != nil || !standing || cur.BuiltAt.IsZero() {
return err
}
}
cur, found, err := rv.r.Of(ctx, module, version)
if err != nil || !found || cur.BuiltAt.IsZero() {
return err return err
} }
if cur, standing = rv.takeKept(ctx, cur); !standing {
return nil
}
rv.arm(ctx, cur) rv.arm(ctx, cur)
if rv.built != nil { if rv.built != nil {
if err := rv.built(ctx, module, version); err != nil { if err := rv.built(ctx, module, version); err != nil {
rv.logf("%v", err) rv.logf("%v", err)
} }
} }
// A published heard before the digests were recorded marks its artifact now, said as one heard after (design 47 G A-415).
marked, unmatched, err := rv.r.Kept(ctx, module, version)
if err != nil {
rv.logf("the published kept on %s %s are not taken in: %v", module, version, err)
}
for _, h := range unmatched {
rv.logf("a published of %s@%s kept on %s %s marks no artifact: its digest %s is none of the built digests %v", h.Name, h.Version, module, version, h.Digest, cur.Artifacts)
// A build whose recorded digest differs from what the holder holds at its version fails loudly at once: the version is taken
// and no artifact is marked for it, so it is never released (design 47 G A-490j).
rv.unreleased(ctx, cur, fmt.Sprintf("the holder holds %s@%s under digest %s, which no artifact of the build carries (%v): the version is taken and is never released",
h.Name, h.Version, h.Digest, cur.Artifacts))
}
for _, m := range marked {
rv.sayPublished(ctx, m, m.Reserved.Artifacts[m.Artifact])
}
return nil return nil
} }
// takeKept takes the published kept on a built reservation in (design 47 G A-415): each whose digest is an artifact's marks it and
// is said as package-published, as one heard after; one whose digest no artifact carries raises version-unreleased at once (A-490j).
// It answers the reservation as the take-in left it, and whether it stands built at its version, so its bound is judged on the
// artifacts the take-in marked (1984/AC5); one whose kept cannot be taken in is answered as it was given, its kept said not taken.
func (rv *reservations) takeKept(ctx context.Context, cur versions.ReservedVersion) (versions.ReservedVersion, bool) {
if len(cur.Kept) == 0 {
return cur, true
}
took, err := rv.r.Kept(ctx, cur.Module, cur.Version)
if err != nil {
rv.logf("the published kept on %s %s are not taken in: %v", cur.Module, cur.Version, err)
return cur, true
}
if !took.Standing {
rv.logf("the published kept on %s %s are not taken in: its reservation stands no more built at the version", cur.Module, cur.Version)
return cur, false
}
for _, h := range took.Unmatched {
rv.logf("a published of %s@%s kept on %s %s marks no artifact: its digest %s is none of the built digests %v", h.Name, h.Version, cur.Module, cur.Version, h.Digest, cur.Artifacts)
// A build whose recorded digest differs from what the holder holds at its version fails loudly at once: the version is taken
// and no artifact is marked for it, so it is never released (design 47 G A-490j).
rv.unreleased(ctx, took.Reserved, fmt.Sprintf("the holder holds %s@%s under digest %s, which no artifact of the build carries (%v): the version is taken and is never released",
h.Name, h.Version, h.Digest, cur.Artifacts))
}
for _, m := range took.Marked {
rv.sayPublished(ctx, m, m.Reserved.Artifacts[m.Artifact])
}
return took.Reserved, true
}
// now is the reservations' clock, the Reserver's, from which a build's end (BuiltAt) is written.
func (rv *reservations) now() time.Time {
if rv.r.Now != nil {
return rv.r.Now().UTC()
}
return time.Now().UTC()
}
// arm arms a built reservation's publish's bound, a key of the state bounds with its own time to live, counted from its build's
// end (BuiltAt): its end with the reservation standing is version-unreleased. One armed already stands; at a look or the start
// after the bound passed, a reservation left with an artifact unpublished is version-unreleased at once (lapsed), and its bound
// is not armed again (issue 1984 note 8, 1984/AC5); one with every artifact published waits for its version-released.
func (rv *reservations) arm(ctx context.Context, v versions.ReservedVersion) { func (rv *reservations) arm(ctx context.Context, v versions.ReservedVersion) {
ends := v.BuiltAt.Add(rv.bound)
left := ends.Sub(rv.now())
if left <= 0 {
if len(v.Missing()) > 0 {
rv.lapsed(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound))
}
return
}
kv := rv.bounds() kv := rv.bounds()
var err error var err error
if kv == nil { if kv == nil {
err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState) err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState)
} else if _, err = kv.Create(ctx, versions.ReservedBoundKey(v.Module, v.Series), versions.EncodeBound("the release of "+v.Module+" "+v.Version, time.Now().Add(rv.bound)), jetstream.KeyTTL(rv.bound)); errors.Is(err, jetstream.ErrKeyExists) { } else if _, err = kv.Create(ctx, versions.ReservedBoundKey(v.Module, v.Series), versions.EncodeBound("the release of "+v.Module+" "+v.Version, ends),
jetstream.KeyTTL(max(time.Second, left.Round(time.Second)))); errors.Is(err, jetstream.ErrKeyExists) {
err = nil err = nil
} }
if err != nil { if err != nil {
rv.logf("the release bound of %s %s is not written, so it is raised unreleased now: %v", v.Module, v.Version, err) rv.logf("the release bound of %s %s is not written, so it is raised unreleased now: %v", v.Module, v.Version, err)
rv.unreleased(ctx, v, fmt.Sprintf("its bound could not be written (%v)", err)) rv.lapsed(ctx, v, fmt.Sprintf("its bound could not be written (%v)", err))
} }
} }
// lapsed raises version-unreleased for a built reservation whose bound ended or could not be armed, only when the module's
// version-unreleased does not stand already (the held writer's Held, design 47 G A-38): a standing one keeps the words it was
// raised with, a holder's refusal of a publish again (ADR 0674 §3) or a digest no artifact carries (A-490j). Those two raise
// through unreleased, as they happen, and write over a standing one with their words.
func (rv *reservations) lapsed(ctx context.Context, v versions.ReservedVersion, why string) {
if rv.found.stands(versions.VersionUnreleased, meshconditionsclient.ScopeModule, v.Module) {
return
}
rv.unreleased(ctx, v, why)
}
// unreleased raises version-unreleased about the module, naming the version and the artifacts missing. // unreleased raises version-unreleased about the module, naming the version and the artifacts missing.
func (rv *reservations) unreleased(ctx context.Context, v versions.ReservedVersion, why string) { func (rv *reservations) unreleased(ctx context.Context, v versions.ReservedVersion, why string) {
missing := v.Missing() missing := v.Missing()
@@ -268,7 +314,9 @@ func (rv *reservations) unreleasedWords(ctx context.Context, v versions.Reserved
} }
// ended is told each change of the state bounds: a reservation's bound whose time ended raises version-unreleased while // ended is told each change of the state bounds: a reservation's bound whose time ended raises version-unreleased while
// the reservation stands built. // the reservation stands built with an artifact unpublished (lapsed: a standing one keeps its words); one with every artifact
// published is not left unmarked (issue 1984 note 8, 1984/AC5) and waits for its version-released, as arm leaves it past the
// bound.
func (rv *reservations) ended(ctx context.Context, e jetstream.KeyValueEntry) bool { func (rv *reservations) ended(ctx context.Context, e jetstream.KeyValueEntry) bool {
key, ok := versions.ReservedBoundOf(e.Key()) key, ok := versions.ReservedBoundOf(e.Key())
if !ok { if !ok {
@@ -278,10 +326,10 @@ func (rv *reservations) ended(ctx context.Context, e jetstream.KeyValueEntry) bo
return true return true
} }
v, found, err := rv.r.At(ctx, key) v, found, err := rv.r.At(ctx, key)
if err != nil || !found || v.BuiltAt.IsZero() { if err != nil || !found || v.BuiltAt.IsZero() || len(v.Missing()) == 0 {
return true return true
} }
rv.unreleased(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound)) rv.lapsed(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound))
return true return true
} }
@@ -294,23 +342,17 @@ func (rv *reservations) dropBound(ctx context.Context, key string) {
} }
} }
// heard takes the catalog's version-released and versions-filled in, and a registry seat's published (published): a // heard takes the catalog's version-released in, and a registry seat's published (published): a
// message that is none of them is left to the others. A state that cannot take one leaves it for the bus to give again. // message that is none of them is left to the others. A state that cannot take one leaves it for the bus to give again.
func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool { func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
switch m.Subject() { switch m.Subject() {
case meshcatalog.SubjectVersionsFilled:
rv.filled.Store(true)
rv.logf("the catalog said versions-filled: versions are reserved from now on")
if rv.wake != nil {
rv.wake(ctx)
}
case meshcatalog.SubjectVersionReleased: case meshcatalog.SubjectVersionReleased:
var ev meshcatalog.VersionReleasedEvent var ev meshcatalog.VersionReleasedEvent
if err := json.Unmarshal(m.Data(), &ev); err != nil || ev.Module == "" || ev.Version == "" { if err := json.Unmarshal(m.Data(), &ev); err != nil || ev.Module == "" || ev.Version == "" {
rv.logf("%s holds what is no version-released, left: %v", m.Subject(), err) rv.logf("%s holds what is no version-released, left: %v", m.Subject(), err)
break break
} }
if err := rv.tagged(ctx, ev); err != nil { if err := rv.release(ctx, ev); err != nil {
rv.logf("%v; heard again", err) rv.logf("%v; heard again", err)
if nakErr := m.Nak(); nakErr != nil { if nakErr := m.Nak(); nakErr != nil {
rv.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr) rv.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
@@ -318,24 +360,6 @@ func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
givenUp(m, "the version-released of "+ev.Module+" "+ev.Version, err, rv.logf) givenUp(m, "the version-released of "+ev.Module+" "+ev.Version, err, rv.logf)
return true return true
} }
gone, err := rv.r.Released(ctx, ev.Module, ev.Version)
if err != nil {
rv.logf("%v; heard again", err)
if nakErr := m.Nak(); nakErr != nil {
rv.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
}
givenUp(m, "the version-released of "+ev.Module+" "+ev.Version, err, rv.logf)
return true
}
for _, k := range gone {
rv.dropBound(ctx, k)
}
if rv.released != nil {
rv.released(ctx, ev.Module, ev.Version)
}
rv.found.clear(ctx, versions.VersionUnreleased, meshconditionsclient.ScopeModule, ev.Module)
rv.found.clear(ctx, versions.VersionHeldElsewhere, meshconditionsclient.ScopeModule, ev.Module)
rv.found.clear(ctx, versions.VersionTaggedElsewhere, meshconditionsclient.ScopeModule, ev.Module)
default: default:
return false return false
} }
@@ -345,6 +369,97 @@ func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
return true return true
} }
// release takes a released version in as the catalog's version-released says it (design 47 G §369): its reservation released,
// its bound and publish item ended and its findings cleared. No git tag is written (design 47 H2 H-A-494).
func (rv *reservations) release(ctx context.Context, ev meshcatalog.VersionReleasedEvent) error {
// A version no reservation holds is acknowledged at once from its one key, never by listing (H-A-514 addendum).
if held, err := rv.r.Holds(ctx, ev.Module, ev.Version); err == nil && !held {
return nil
}
gone, err := rv.r.Released(ctx, ev.Module, ev.Version)
if err != nil {
return err
}
for _, k := range gone {
rv.dropBound(ctx, k)
}
if rv.released != nil {
rv.released(ctx, ev.Module, ev.Version)
}
rv.found.clear(ctx, versions.VersionUnreleased, meshconditionsclient.ScopeModule, ev.Module)
rv.found.clear(ctx, versions.VersionHeldElsewhere, meshconditionsclient.ScopeModule, ev.Module)
rv.found.clear(ctx, versions.VersionTaggedElsewhere, meshconditionsclient.ScopeModule, ev.Module) // one raised before H-A-494
return nil
}
// releasedAtStart takes in, at the builder's start, every built, unreleased reservation whose version the catalog's verb versions
// holds released, as its version-released would (design 47 H2 H-A-484 addendum): a version-released the bus gave up on, or one
// said while the builder was away, is taken all the same, its reservation released and its publish item ended; no tag is written
// (design 47 H2 H-A-494).
// A module whose versions cannot be read, and a release that is not taken, are said and left to its next version-released.
// Before that, a standing reservation with no digests recorded whose build key is done has them recorded from the done key
// (design 47 H2 H-A-492), so it is held against the released versions too. Every built reservation not released is taken in as
// its record's end would have (issue 1984 note 8, 1984/AC5): the published kept on it taken in and said, and then its bound armed
// on the reservation as that take-in left it.
func (rv *reservations) releasedAtStart(ctx context.Context) {
all, err := rv.r.All(ctx)
if err != nil {
rv.logf("the reservations are not held against the catalog's released versions at the start: %v", err)
return
}
if rv.recordedAtStart(ctx, all) {
if all, err = rv.r.All(ctx); err != nil {
rv.logf("the reservations are not held against the catalog's released versions at the start: %v", err)
return
}
}
read := map[string][]string{}
for _, v := range builtOf(all) {
if versions.NotStanding(v, true) != "" {
continue
}
released, ok := read[v.Module]
if !ok {
if released, err = rv.r.ReleasedOf(ctx, v.Module); err != nil {
rv.logf("%s: the catalog's released versions cannot be read at the start, so its built reservations wait for its next version-released: %v", v.Module, err)
}
read[v.Module] = released
}
if !slices.Contains(released, v.Version) {
// Taken in as its record's end would have (1984/AC5); its publish item is asked by AskAllDone, next.
if cur, standing := rv.takeKept(ctx, v); standing {
rv.arm(ctx, cur)
}
continue
}
if err := rv.release(ctx, meshcatalog.VersionReleasedEvent{Module: v.Module, Version: v.Version}); err != nil {
rv.logf("%s %s is released in the catalog and not taken in at the start: %v", v.Module, v.Version, err)
continue
}
rv.logf("%s %s is released in the catalog: taken in at the start, as its version-released", v.Module, v.Version)
}
}
// recordedAtStart records the digests of every standing reservation that has not all recorded and whose build key is done (design
// 47 H2 H-A-492): a record its build's end lost, whole or in part. It answers whether one was recorded; one that cannot be is said.
func (rv *reservations) recordedAtStart(ctx context.Context, all []versions.ReservedVersion) bool {
if rv.recordAgain == nil {
return false
}
recorded := false
for _, v := range all {
if !v.BuiltAt.IsZero() || v.Fingerprint == "" || versions.NotStanding(v, true) != "" {
continue
}
version, err := rv.recordAgain(ctx, v.Module, v.Fingerprint, "at the builder's start")
if err != nil {
rv.logf("%v", err)
}
recorded = recorded || version != ""
}
return recorded
}
// published marks the artifacts of the reservation a registry seat's published names (its version and digest). inProgress is told // published marks the artifacts of the reservation a registry seat's published names (its version and digest). inProgress is told
// before a pass that may read many reservations, so the handler says in progress to the bus (design 47 H H-A-280); nil is told // before a pass that may read many reservations, so the handler says in progress to the bus (design 47 H H-A-280); nil is told
// nothing. // nothing.
@@ -404,33 +519,6 @@ func (rv *reservations) dropped(ctx context.Context, module, series, by, why str
return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s)", module, series, by, why), nil return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s)", module, series, by, why), nil
} }
// tagged writes the git tag of a released version (design 47 G §370): on the catalog's version-released, through the seat
// git's verb tag, at the commit the reservation of that version was made from. A version with no reservation (a superseded
// build's version is never released, and the key of a version released by another builder is gone) or one that names no
// tag (a module with no Go package) is tagged nowhere. A tag the forge could not write is an error, the message heard again.
func (rv *reservations) tagged(ctx context.Context, ev meshcatalog.VersionReleasedEvent) error {
res, found, err := rv.r.Of(ctx, ev.Module, ev.Version)
if err != nil {
return fmt.Errorf("the reservation of %s %s cannot be read to tag it: %w", ev.Module, ev.Version, err)
}
if !found || res.Tag == "" || res.Commit == "" {
return nil
}
raw, err := rv.call("seat:"+git.Seat+".tag", git.TagInput{Repository: res.Repository, Commit: res.Commit, Tag: res.Tag})
if err != nil {
return fmt.Errorf("the tag %s of %s is not written: %w", res.Tag, ev.Module, err)
}
var a git.TagAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return fmt.Errorf("the git seat answered what is no tag answer for %s: %w", res.Tag, err)
}
if a.Error != "" || !a.Performed {
return fmt.Errorf("the tag %s of %s is not written: %s (%s)", res.Tag, ev.Module, a.Error, a.ErrorKind)
}
rv.logf("%s is tagged %s at %s", ev.Module, res.Tag, res.Commit)
return nil
}
// noMark says why a published marked nothing, from the reservations the published read (design 47 H H-A-280: no second read): // noMark says why a published marked nothing, from the reservations the published read (design 47 H H-A-280: no second read):
// what each holds of digests, and how many stand at that version by the index by version (its one key, no reservation read). // what each holds of digests, and how many stand at that version by the index by version (its one key, no reservation read).
func (rv *reservations) noMark(ctx context.Context, o versions.Outcome, read []versions.ReadReservation) string { func (rv *reservations) noMark(ctx context.Context, o versions.Outcome, read []versions.ReadReservation) string {
@@ -502,19 +590,6 @@ func (rv *reservations) heldElsewhere(ctx context.Context, module, why string) {
needs: "builder_reserved shows the reservation and its withdrawn numbers; the registry seat's versions shows what it holds."}) needs: "builder_reserved shows the reservation and its withdrawn numbers; the registry seat's versions shows what it holds."})
} }
// taggedElsewhere raises version-tagged-elsewhere about module (design 47 H2 §796): numbers whose git tag stands at another
// commit were skipped at reserving; a tag is never moved. Cleared at the module's next version-released.
func (rv *reservations) taggedElsewhere(ctx context.Context, module string, skipped []string) {
why := "the tags of " + strings.Join(skipped, ", ") + " stand at another commit, so the reserve skipped them"
rv.logf("%s: %s", module, why)
rv.found.raise(ctx, finding{kind: versions.VersionTaggedElsewhere, scope: meshconditionsclient.ScopeModule, id: module,
summary: module + ": " + why,
headline: "A number whose tag stands at another commit is not used",
explanation: "The repository holds a tag of " + module + " at a commit other than the build's: " + why + ". A tag is never moved.",
resolved: "The catalog says version-released for " + module + ".",
needs: "builder_reserved shows the reservation; the seat git's tags shows each tag with its commit."})
}
// movedElsewhere takes a done build whose number a registry holds at another digest off that number (design 47 H H-A-275, // movedElsewhere takes a done build whose number a registry holds at another digest off that number (design 47 H H-A-275,
// H-A-279): every artifact carries its version from its build, so no digest survives a move. The number is withdrawn as a gap // H-A-279): every artifact carries its version from its build, so no digest survives a move. The number is withdrawn as a gap
// (H-A-226), the finding raised naming both digests, and the build of the same fingerprint asked again (the build-again path of a // (H-A-226), the finding raised naming both digests, and the build of the same fingerprint asked again (the build-again path of a
@@ -7,6 +7,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"slices" "slices"
"strings" "strings"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -14,6 +15,7 @@ import (
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go" stdio "git.novox.be/novox/mesh-sdk/go"
@@ -24,8 +26,9 @@ import (
// memReserve is the state reserved in memory. // memReserve is the state reserved in memory.
type memReserve struct { type memReserve struct {
vals map[string][]byte vals map[string][]byte
revs map[string]uint64 revs map[string]uint64
lists int // how often its keys were listed
} }
func (m *memReserve) Get(_ context.Context, key string) ([]byte, uint64, bool, error) { func (m *memReserve) Get(_ context.Context, key string) ([]byte, uint64, bool, error) {
@@ -47,6 +50,7 @@ func (m *memReserve) Update(_ context.Context, key string, v []byte, rev uint64)
return rev + 1, nil return rev + 1, nil
} }
func (m *memReserve) KeysOf(_ context.Context, filter string) ([]string, error) { func (m *memReserve) KeysOf(_ context.Context, filter string) ([]string, error) {
m.lists++
var out []string var out []string
for k := range m.vals { for k := range m.vals {
if versions.FilterMatches(filter, k) { // as the bus reads a filter if versions.FilterMatches(filter, k) { // as the bus reads a filter
@@ -60,14 +64,18 @@ func (m *memReserve) Delete(_ context.Context, key string) error {
return nil return nil
} }
// boundsKV keeps the keys created and deleted in the state bounds. // boundsKV keeps the keys created and deleted in the state bounds, and with vals each created key's value.
type boundsKV struct { type boundsKV struct {
jetstream.KeyValue jetstream.KeyValue
keys map[string]bool keys map[string]bool
vals map[string][]byte
} }
func (b *boundsKV) Create(_ context.Context, key string, _ []byte, _ ...jetstream.KVCreateOpt) (uint64, error) { func (b *boundsKV) Create(_ context.Context, key string, v []byte, _ ...jetstream.KVCreateOpt) (uint64, error) {
b.keys[key] = true b.keys[key] = true
if b.vals != nil {
b.vals[key] = v
}
return 1, nil return 1, nil
} }
func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error { func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
@@ -75,33 +83,23 @@ func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDelete
return nil return nil
} }
// TestTheCatalogsWordsMoveTheReservations: design 47 G §369, §372 (test 102) — versions-filled opens the reserving and wakes // TestTheCatalogsWordsMoveTheReservations: design 47 G §369 (test 102) — a built reservation arms its bound and its end raises version-unreleased naming the artifacts
// the builds that wait; a built reservation arms its bound and its end raises version-unreleased naming the artifacts
// missing; the catalog's version-released deletes the key and the bound and clears the finding; builder_reserved_drop drops one. // missing; the catalog's version-released deletes the key and the bound and clears the finding; builder_reserved_drop drops one.
func TestTheCatalogsWordsMoveTheReservations(t *testing.T) { func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
ctx := context.Background() ctx := context.Background()
st := &memFindings{vals: map[string][]byte{}} st := &memFindings{vals: map[string][]byte{}}
found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }} found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
bounds := &boundsKV{keys: map[string]bool{}} bounds := &boundsKV{keys: map[string]bool{}}
woke := 0
call := func(addr string, body any) (json.RawMessage, error) { call := func(addr string, body any) (json.RawMessage, error) {
if addr != "seat:mesh-catalog.versions" { if addr != "seat:mesh-catalog.versions" {
t.Errorf("the released versions were asked of %q", addr) t.Errorf("the released versions were asked of %q", addr)
} }
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m", Versions: []meshcatalog.VersionEntry{{Module: "m", Version: "1.4.2"}}}) return json.Marshal(meshcatalog.VersionsAnswer{Module: "m", Versions: []meshcatalog.VersionEntry{{Module: "m", Version: "1.4.2"}}})
} }
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, t.Logf)
func(context.Context) { woke++ }, t.Logf)
var items []string // design 47 G A-457a: the end of a build asks its publish, the release ends it var items []string // design 47 G A-457a: the end of a build asks its publish, the release ends it
rv.built = func(_ context.Context, m, v string) error { items = append(items, "asked "+m+" "+v); return nil } rv.built = func(_ context.Context, m, v string) error { items = append(items, "asked "+m+" "+v); return nil }
rv.released = func(_ context.Context, m, v string) { items = append(items, "ended "+m+" "+v) } rv.released = func(_ context.Context, m, v string) { items = append(items, "ended "+m+" "+v) }
if _, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}); err == nil || rv.Filled() {
t.Fatalf("a version was reserved before versions-filled (%v)", err)
}
filled := &wakeMsg{subject: meshcatalog.SubjectVersionsFilled, data: []byte(`{"v":1}`)}
if !rv.heard(ctx, filled) || !filled.acked || !rv.Filled() || woke != 1 {
t.Fatalf("versions-filled: acked %v, filled %v, woke %d", filled.acked, rv.Filled(), woke)
}
var said []meshbuilds.PackagePublished var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil } rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41}) res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
@@ -156,89 +154,131 @@ func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
} }
} }
// TestAReleasedVersionIsTaggedAtTheCommitItWasBuiltFrom: design 47 G §370 — the git tag go/vMAJOR.MINOR.PATCH is written through // TestAReleasedVersionWritesNoTag: design 47 H2 H-A-494 — the builder writes no git tag at a release, and numbers a series from the
// the seat git's tag on the catalog's version-released, at the commit the version's reservation was made from; a module with no // catalog's versions and the registries' alone: the catalog's version-released releases the reservation with no call of the seat
// Go package, and a version never released (a superseded build's), are tagged nowhere; a tag the forge did not write leaves // git, a reservation written before (one naming a tag) included; the start's take-in of a version the catalog holds released
// version-released to be heard again with the reservation standing. // (H-A-484 c) the same; and a reserve reads no git tag, a tag standing at another commit no reason to skip a number.
func TestAReleasedVersionIsTaggedAtTheCommitItWasBuiltFrom(t *testing.T) { func TestAReleasedVersionWritesNoTag(t *testing.T) {
ctx := context.Background() ctx := context.Background()
var tags []git.TagInput var gitCalls []string // every call of the seat git: none is made
refuse := "" var catalog []meshcatalog.VersionEntry // the released versions the catalog's verb versions answers
var standing []git.Tag // the tags the seat git's tags answers (design 47 H2 §796)
call := func(addr string, body any) (json.RawMessage, error) { call := func(addr string, body any) (json.RawMessage, error) {
switch addr { if strings.HasPrefix(addr, "seat:git.") {
case "seat:git.tags": gitCalls = append(gitCalls, addr)
return json.Marshal(map[string]any{"form": 2, "tags": standing, "a-field-of-a-later-form": true}) if addr == "seat:git.tags" { // a tag standing at another commit, as the forge may still hold one
case "seat:git.tag": return json.Marshal(map[string]any{"form": 2, "tags": []git.Tag{{Tag: "go/v0.2.0", Commit: "elsewhere"}}})
default: }
return json.Marshal(meshcatalog.VersionsAnswer{}) return json.Marshal(git.TagAnswer{Performed: true})
} }
tags = append(tags, body.(git.TagInput)) return json.Marshal(meshcatalog.VersionsAnswer{Versions: catalog})
return json.Marshal(git.TagAnswer{Performed: refuse == "", Error: refuse})
} }
fw := &memFindings{vals: map[string][]byte{}} fw := &memFindings{vals: map[string][]byte{}}
found := &findings{module: builds.BuilderModule, w: fw, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }} found := &findings{module: builds.BuilderModule, w: fw, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf) store := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
rv.filled.Store(true) rv := newReservations(store, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf)
// Design 47 H2 §796: the tag names the Go module's directory, read from its module path: mesh-sdk's `go` here. rv.names = func(_ context.Context, _, artifact string) (string, bool, error) {
rv.r.Names = func(_ context.Context, module, artifact string) (string, bool, error) { return "git.example/o/r/go", artifact == "lib", nil
return "git.example/o/r/go", artifact == "lib" || artifact == "pkg", nil
} }
goPkg := versions.Source{Repository: "o/r", Commit: "c0ffee", GoPackage: true, GoArtifact: "lib"} goPkg := versions.Source{Repository: "o/r", Commit: "c0ffee", Fingerprint: "fpA"}
if _, err := rv.Reserve(ctx, "pkg", "0.1", []string{"pkg:lib"}, goPkg); err != nil { // oldRecord rewrites a reservation as one written before H-A-494, naming the tag its release was to be written as.
t.Fatal(err) oldRecord := func(module, series, tag string) {
} key := versions.ReservedKey(module, series)
if _, err := rv.Reserve(ctx, "prog", "2.0", []string{"prog:bin"}, versions.Source{Repository: "o/p", Commit: "beef"}); err != nil { var v versions.ReservedVersion
t.Fatal(err) if err := json.Unmarshal(store.vals[key], &v); err != nil {
t.Fatal(err)
}
v.Tag = tag
store.vals[key], _ = json.Marshal(v)
} }
release := func(module, version string) *wakeMsg { release := func(module, version string) *wakeMsg {
m := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"` + module + `","version":"` + version + `","source":1,"artifacts":[]}`)} m := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"` + module + `","version":"` + version + `","source":1,"artifacts":[]}`)}
rv.heard(ctx, m) rv.heard(ctx, m)
return m return m
} }
if m := release("prog", "2.0.0"); !m.acked || len(tags) != 0 { // The release path: a Go package's version-released releases it, acknowledged, with no tag written.
t.Fatalf("a module with no Go package: acked %v, tags %v; want none written", m.acked, tags) if v, err := rv.Reserve(ctx, "pkg", "0.1", []string{"pkg:lib"}, goPkg); err != nil || v.Tag != "" {
t.Fatalf("reserved %+v (%v), want a reservation naming no tag", v, err)
} }
refuse = "forge down" oldRecord("pkg", "0.1", "go/v0.1.0")
if m := release("pkg", "0.1.0"); !m.naked || m.acked { if m := release("pkg", "0.1.0"); !m.acked || m.naked {
t.Fatalf("a tag the forge did not write: naked %v acked %v; want the release heard again", m.naked, m.acked) t.Fatalf("the release: acked %v naked %v; want it acknowledged", m.acked, m.naked)
} }
if all, _ := rv.r.All(ctx); len(all) != 1 { if len(gitCalls) != 0 {
t.Fatalf("the reservation went with an unwritten tag: %v", all) t.Errorf("the release called the seat git: %v; want no tag written", gitCalls)
gitCalls = nil
} }
refuse = "" if all, _ := rv.r.All(ctx); len(all) != 0 {
tags = nil t.Fatalf("the released version still stands: %v", all)
if m := release("pkg", "0.1.0"); !m.acked || len(tags) != 1 || tags[0] != (git.TagInput{Repository: "o/r", Commit: "c0ffee", Tag: "go/v0.1.0"}) {
t.Fatalf("the release: acked %v, tags %+v; want go/v0.1.0 at c0ffee of o/r", m.acked, tags)
} }
tags = nil // Design 47 H2 H-A-514 addendum: a version-released of a version no reservation holds is acknowledged at once from its
if _, err := rv.Reserve(ctx, "pkg", "0.1", []string{"pkg:lib"}, goPkg); err != nil { // build A: 0.1.0 (the stub catalog holds none released) // series' one key, the module's keys never listed.
if _, err := rv.Reserve(ctx, "late", "0.2", []string{"late:bin"}, versions.Source{Repository: "o/l", Commit: "c1", Fingerprint: "fpL"}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if v, err := rv.Reserve(ctx, "pkg", "0.1", []string{"pkg:lib"}, versions.Source{Repository: "o/r", Commit: "b0b", GoPackage: true, GoArtifact: "lib"}); err != nil || v.Version != "0.1.1" { // build B supersedes A store.lists = 0
t.Fatalf("second build reserved %q (%v)", v.Version, err) if m := release("late", "0.2.7"); !m.acked || m.naked || store.lists != 0 {
t.Fatalf("a release no reservation holds: acked %v naked %v, the keys listed %d times; want it acknowledged with none", m.acked, m.naked, store.lists)
} }
release("pkg", "0.1.0") // A's version is never released in fact; were it said, it is no reservation of the key if _, standing, _ := rv.r.Of(ctx, "late", "0.2.0"); !standing {
if len(tags) != 0 { t.Fatal("a release of another version took the standing reservation late 0.2.0")
t.Fatalf("a superseded build's version was tagged: %+v", tags)
} }
if release("pkg", "0.1.1"); len(tags) != 1 || tags[0].Commit != "b0b" { if _, err := rv.r.Drop(ctx, "late", "0.2"); err != nil {
t.Fatalf("the newer build's version: tags %+v; want go/v0.1.1 at b0b", tags) t.Fatal(err)
} }
// Design 47 H2 §796: a tag standing at another commit makes the next number and the finding version-tagged-elsewhere, which // The start check (H-A-484 c): a built reservation the catalog holds released is released at the start, no tag written; one
// clears at the module's next version-released. // not built, or not released, stands.
standing = []git.Tag{{Tag: "go/v0.2.0", Commit: "elsewhere"}, {Tag: "go/v0.2.1", Commit: "elsewhere"}} // Design 47 H2 H-A-492: at the start, a standing reservation with no digests recorded whose build key is done has them
if v, err := rv.Reserve(ctx, "pkg", "0.2", []string{"pkg:lib"}, goPkg); err != nil || v.Version != "0.2.2" || v.Tag != "go/v0.2.2" { // recorded (the builder's RecordAgain), and is then held against the released versions as a built one is.
t.Fatalf("reserved %+v (%v) with 0.2.0 and 0.2.1 tagged elsewhere, want 0.2.2 tagged go/v0.2.2", v, err) if _, err := rv.Reserve(ctx, "rec", "0.1", []string{"rec:bin"}, versions.Source{Repository: "o/q", Commit: "abc", Fingerprint: "fpR"}); err != nil {
t.Fatal(err)
}
var recordedAt []string
rv.recordAgain = func(ctx context.Context, module, fp, when string) (string, error) {
recordedAt = append(recordedAt, module+" "+fp+" "+when)
_, _, err := rv.r.Built(ctx, module, "0.1.0", map[string]string{"rec:bin": "sha256:bb"}, nil) // its done key's digest
return "0.1.0", err
}
catalog = []meshcatalog.VersionEntry{{Module: "rec", Version: "0.1.0"}}
rv.releasedAtStart(ctx)
if _, standing, _ := rv.r.Of(ctx, "rec", "0.1.0"); standing || !slices.Equal(recordedAt, []string{"rec fpR at the builder's start"}) {
t.Fatalf("at the start, rec 0.1.0 unrecorded and released: standing %v, recorded %q; want it recorded once at the start and released", standing, recordedAt)
}
catalog, rv.recordAgain = nil, nil
var ended []string
rv.released = func(_ context.Context, module, version string) { ended = append(ended, module+" "+version) }
if _, err := rv.Reserve(ctx, "pkg", "0.1", []string{"pkg:lib"}, versions.Source{Repository: "o/r", Commit: "b0b", Fingerprint: "fpB"}); err != nil {
t.Fatal(err) // 0.1.0 again: the stub catalog holds none released
}
oldRecord("pkg", "0.1", "go/v0.1.0")
rv.releasedAtStart(ctx) // built nothing yet: nothing taken
if all, _ := rv.r.All(ctx); len(all) != 1 {
t.Fatalf("at the start with no build done: reservations %v; want the reservation standing", all)
}
if _, _, err := rv.r.Built(ctx, "pkg", "0.1.0", map[string]string{"pkg:lib": "sha256:aa"}, nil); err != nil {
t.Fatal(err)
}
rv.releasedAtStart(ctx) // the catalog holds none released: it stands
if all, _ := rv.r.All(ctx); len(all) != 1 {
t.Fatalf("at the start with nothing released: reservations %v; want the reservation standing", all)
}
catalog = []meshcatalog.VersionEntry{{Module: "pkg", Version: "0.1.0"}}
rv.releasedAtStart(ctx)
if all, _ := rv.r.All(ctx); len(all) != 0 || !slices.Equal(ended, []string{"pkg 0.1.0"}) {
t.Fatalf("at the start with 0.1.0 released: reservations %v, items ended %v; want it released and its item ended", all, ended)
}
if len(gitCalls) != 0 {
t.Errorf("the start check called the seat git: %v; want no tag written", gitCalls)
gitCalls = nil
}
catalog, rv.released = nil, nil
// Numbering reads no tag: the seat git would answer go/v0.2.0 at another commit, and 0.2.0 is reserved all the same.
if v, err := rv.Reserve(ctx, "pkg", "0.2", []string{"pkg:lib"}, goPkg); err != nil || v.Version != "0.2.0" || v.Tag != "" || len(gitCalls) != 0 {
t.Errorf("reserved %+v (%v), git calls %v; want 0.2.0 naming no tag, no git tag read", v, err, gitCalls)
} }
key := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "pkg", versions.VersionTaggedElsewhere) key := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "pkg", versions.VersionTaggedElsewhere)
if got, err := decodeFinding(fw.vals[key]); err != nil || !strings.Contains(got.Summary, "0.2.0") || !strings.Contains(got.Summary, "0.2.1") { if fw.vals[key] != nil {
t.Fatalf("the finding %s = %+v (%v), want it naming 0.2.0 and 0.2.1", key, got, err) t.Errorf("a reserve raised %s", key)
} }
if release("pkg", "0.2.2"); fw.vals[key] != nil {
t.Errorf("version-released of pkg left %s standing", key)
}
standing = nil
// Design 47 H2 §805, H-A-420 (2): a package's number newly reserved is said as version-reserved, its path the package's name // Design 47 H2 §805, H-A-420 (2): a package's number newly reserved is said as version-reserved, its path the package's name
// and its revision the indexer's `<branch>.<n>`; a reservation kept as it stood, an artifact that is no package and a // and its revision the indexer's `<branch>.<n>`; a reservation kept as it stood, an artifact that is no package and a
// reservation naming no catalog revision say none. // reservation naming no catalog revision say none.
@@ -247,7 +287,7 @@ func TestAReleasedVersionIsTaggedAtTheCommitItWasBuiltFrom(t *testing.T) {
return "git.example/o/r/" + artifact, module == "lib2" && artifact == "pkg", nil return "git.example/o/r/" + artifact, module == "lib2" && artifact == "pkg", nil
} }
rv.sayReserved = func(_ context.Context, ev meshbuilds.VersionReservedEvent) error { said = append(said, ev); return nil } rv.sayReserved = func(_ context.Context, ev meshbuilds.VersionReservedEvent) error { said = append(said, ev); return nil }
at := versions.Source{Repository: "o/r", Commit: "c1", Fingerprint: "src2:l2", GoPackage: true, GoArtifact: "pkg", Branch: "main", CatalogRevision: 158} at := versions.Source{Repository: "o/r", Commit: "c1", Fingerprint: "src2:l2", Branch: "main", CatalogRevision: 158}
for range 2 { for range 2 {
if _, err := rv.Reserve(ctx, "lib2", "0.3", []string{"lib2:pkg", "lib2:bin"}, at); err != nil { if _, err := rv.Reserve(ctx, "lib2", "0.3", []string{"lib2:pkg", "lib2:bin"}, at); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -274,10 +314,9 @@ func TestAPublishedHeardBeforeTheDigestsIsSaidWhenTheBuildRecordsThem(t *testing
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
} }
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, logf) &findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, logf)
var said []meshbuilds.PackagePublished var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil } rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
rv.filled.Store(true)
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41}) res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -311,6 +350,251 @@ func TestAPublishedHeardBeforeTheDigestsIsSaidWhenTheBuildRecordsThem(t *testing
} }
} }
// TestABuildsDigestsAreRecordedInOneWrite: issue 1984 note 8, 1984/AC4 — recording a build's digests is one compare-and-set of
// its reservation and one reindex for all its artifacts (39 here, as mesh-delivery-contracts 0.1.108 had); a record tried again
// after one that timed out writes only what that one left (an artifact recorded already is skipped), and nothing when every
// digest stands recorded.
func TestABuildsDigestsAreRecordedInOneWrite(t *testing.T) {
ctx := context.Background()
store := &countedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, writes: map[string]int{}}
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, t.Logf)
var asked []string
rv.built = func(_ context.Context, m, v string) error { asked = append(asked, m+" "+v); return nil }
refsOf := func(module string) ([]string, map[string]string) {
var refs []string
digests := map[string]string{}
for i := range 39 {
ref := fmt.Sprintf("%s:a%02d", module, i)
refs, digests[ref] = append(refs, ref), fmt.Sprintf("sha256:%s%02d", module, i)
}
return refs, digests
}
built := func(module string) versions.ReservedVersion {
t.Helper()
v, found, err := rv.r.Of(ctx, module, "")
if err != nil || !found {
t.Fatalf("%s: no reservation (%v)", module, err)
}
return v
}
refs, digests := refsOf("c")
res, err := rv.Reserve(ctx, "c", "0.1", refs, versions.Source{Fingerprint: "fpC"})
if err != nil {
t.Fatal(err)
}
key := versions.ReservedKey("c", "0.1")
clear(store.writes)
store.indexReads = 0
if err := rv.Built(ctx, "c", res.Version, digests, nil); err != nil {
t.Fatal(err)
}
// One reindex reads each index key the built reservation stands under (its version and its 39 digests) and the one it leaves
// (its version's unbuilt): 41 reads, never one reindex per artifact.
if w, r := store.writes[key], store.indexReads; w != 1 || r > 41 {
t.Errorf("39 digests recorded with %d writes of %s and %d reads of the index, want one write and one reindex (at most 41 reads) (1984/AC4)", w, key, r)
}
if v := built("c"); v.BuiltAt.IsZero() || len(v.Missing()) != 39 || !slices.Equal(asked, []string{"c " + res.Version}) {
t.Errorf("after the record: built at %v, %d unpublished, publish items asked %v; want the build ended, 39 awaited and its item asked once", v.BuiltAt, len(v.Missing()), asked)
}
// A record that timed out left 30 of 39 digests written and the build not ended (the form the record of one artifact at a
// time wrote): the record tried again writes the reservation once, skipping the 30.
refs, digests = refsOf("d")
res, err = rv.Reserve(ctx, "d", "0.1", refs, versions.Source{Fingerprint: "fpD"})
if err != nil {
t.Fatal(err)
}
key = versions.ReservedKey("d", "0.1")
left := res
left.Artifacts = map[string]string{}
for i, ref := range refs {
left.Artifacts[ref] = map[bool]string{true: digests[ref], false: ""}[i < 30]
}
store.vals[key], _ = json.Marshal(left)
clear(store.writes)
if err := rv.Built(ctx, "d", res.Version, digests, nil); err != nil {
t.Fatal(err)
}
if w := store.writes[key]; w != 1 || built("d").BuiltAt.IsZero() {
t.Errorf("the record tried again wrote %s %d times (built at %v), want once, the 30 recorded skipped (1984/AC4)", key, w, built("d").BuiltAt)
}
// Tried again once more, every digest recorded: nothing is written.
clear(store.writes)
if err := rv.Built(ctx, "d", res.Version, digests, nil); err != nil {
t.Fatal(err)
}
if w := store.writes[key]; w != 0 {
t.Errorf("a record of digests all recorded wrote %s %d times, want none (1984/AC4)", key, w)
}
}
// TestABuiltReservationIsTakenInFromItsState: issue 1984 note 8, 1984/AC5 — what follows a build's record follows the
// reservation's state, not whether the record before ended: at a look (the builder's RecordAgain hands a recorded reservation to
// Built with its digests) and at the start, a built reservation with published kept on it takes them in, says package-published
// and arms its bound, counted from its build's end; one left unmarked past its bound raises version-unreleased, its bound not
// armed again, and one whose kept published mark every artifact raises nothing. A version-unreleased standing with a holder's
// words keeps them past the bound and at the bound's end.
func TestABuiltReservationIsTakenInFromItsState(t *testing.T) {
ctx := context.Background()
store := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
fs := &memFindings{vals: map[string][]byte{}}
bounds := &boundsKV{keys: map[string]bool{}, vals: map[string][]byte{}}
rv := newReservations(store, none, func() jetstream.KeyValue { return bounds },
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, t.Logf)
var said []string
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error {
said = append(said, p.Artifact+"@"+p.Version+" "+p.Digest)
return nil
}
var asked []string
rv.built = func(_ context.Context, m, v string) error { asked = append(asked, m+" "+v); return nil }
now := time.Now().UTC()
// recordedLost is module's reservation as a record whose end was lost leaves it: the published of the artifacts heard (a, b)
// heard before the digests kept on it, every digest recorded and the build ended at builtAt, and nothing after (no bound, the
// kept published not taken in).
recordedLost := func(module string, builtAt time.Time, heard ...string) versions.ReservedVersion {
t.Helper()
res, err := rv.Reserve(ctx, module, "0.1", []string{module + ":a", module + ":b"}, versions.Source{Fingerprint: "fp" + module, Branch: "main", Revision: 41})
if err != nil {
t.Fatal(err)
}
for _, a := range heard {
rv.published(ctx, versions.Outcome{Name: module + "-" + a, Version: res.Version, Digest: "sha256:" + module + a}, nil)
}
v, _, _ := rv.r.Of(ctx, module, res.Version)
if len(v.Kept) != len(heard) {
t.Fatalf("%s: kept %v, want the published heard before the digests kept", module, v.Kept)
}
v.Artifacts = map[string]string{module + ":a": "sha256:" + module + "a", module + ":b": "sha256:" + module + "b"}
v.BuiltAt = builtAt
key := versions.ReservedKey(module, "0.1")
store.vals[key], _ = json.Marshal(v)
return v
}
unreleased := func(module string) string {
return string(fs.vals[meshconditionsclient.Key(meshconditionsclient.ScopeModule, module, versions.VersionUnreleased)])
}
boundEnds := func(module string) time.Time {
var b versions.Bound
_ = json.Unmarshal(bounds.vals[versions.ReservedBoundKey(module, "0.1")], &b)
return b.Ends
}
t.Run("at a look", func(t *testing.T) {
v := recordedLost("look", now.Add(-5*time.Minute), "a")
said, asked = nil, nil
if err := rv.Built(ctx, "look", v.Version, v.Artifacts, nil); err != nil {
t.Fatal(err)
}
// Its publish item is asked as the build's end asks it: it stands until its release (design 47 G A-456b).
if !slices.Equal(said, []string{"look:a@" + v.Version + " sha256:looka"}) || !slices.Equal(asked, []string{"look " + v.Version}) {
t.Errorf("at a look: said %v, publish items asked %v; want look:a's package-published said and its item asked", said, asked)
}
if ends := boundEnds("look"); !ends.Equal(v.BuiltAt.Add(versions.UnreleasedBound)) {
t.Errorf("the bound armed at a look ends %v, want %v: counted from the build's end", ends, v.BuiltAt.Add(versions.UnreleasedBound))
}
if cur, _, _ := rv.r.Of(ctx, "look", v.Version); len(cur.Kept) != 0 || !cur.Published["look:a"] {
t.Errorf("after the look: kept %v, published %v; want the kept published taken in", cur.Kept, cur.Published)
}
})
t.Run("at the start", func(t *testing.T) {
v := recordedLost("start", now.Add(-time.Minute), "a")
said = nil
rv.releasedAtStart(ctx)
if !slices.Contains(said, "start:a@"+v.Version+" sha256:starta") || !bounds.keys[versions.ReservedBoundKey("start", "0.1")] {
t.Errorf("at the start: said %v, bounds %v; want start:a's package-published said and its bound armed", said, bounds.keys)
}
if unreleased("start") != "" {
t.Errorf("a built reservation within its bound raised %s", unreleased("start"))
}
})
t.Run("past its bound", func(t *testing.T) {
for _, when := range []string{"a look", "the start"} {
module := map[string]string{"a look": "pastlook", "the start": "paststart"}[when]
v := recordedLost(module, now.Add(-versions.UnreleasedBound-time.Minute), "a")
takeIn := func() {
if when == "a look" {
if err := rv.Built(ctx, module, v.Version, v.Artifacts, nil); err != nil {
t.Fatal(err)
}
} else {
rv.releasedAtStart(ctx)
}
}
takeIn()
if got := unreleased(module); !strings.Contains(got, module+":b unpublished") || !strings.Contains(got, v.Version) {
t.Errorf("at %s, a built reservation left unmarked past its bound raised %q, want version-unreleased naming %s:b of %s", when, got, module, v.Version)
}
if bounds.keys[versions.ReservedBoundKey(module, "0.1")] {
t.Errorf("at %s, the bound of a reservation past it was armed again", when)
}
// One standing is left as it was raised: the next take-in does not write it again over the holder's words (ADR 0674 §3).
rv.unreleasedWords(ctx, v, "the holder refused the publish again: no space left")
takeIn()
if got := unreleased(module); !strings.Contains(got, "no space left") || strings.Contains(got, "nothing within") {
t.Errorf("at %s again, version-unreleased reads %q, want the holder's words it was left with", when, got)
}
// Note 8's own case: every artifact's published kept on it is taken in before its bound is judged, so nothing is
// unpublished and nothing is raised; each is said as package-published.
module = map[string]string{"a look": "keptlook", "the start": "keptstart"}[when]
v = recordedLost(module, now.Add(-versions.UnreleasedBound-time.Minute), "a", "b")
said = nil
takeIn()
if got := unreleased(module); got != "" {
t.Errorf("at %s, a reservation past its bound whose kept published mark every artifact raised %q, want no version-unreleased", when, got)
}
if !slices.Contains(said, module+":a@"+v.Version+" sha256:"+module+"a") || !slices.Contains(said, module+":b@"+v.Version+" sha256:"+module+"b") {
t.Errorf("at %s, said %v, want package-published of %s:a and %s:b", when, said, module, module)
}
if bounds.keys[versions.ReservedBoundKey(module, "0.1")] {
t.Errorf("at %s, the bound of a reservation past it was armed", when)
}
}
})
t.Run("its bound ending", func(t *testing.T) {
v := recordedLost("ends", now.Add(-time.Minute), "a")
if err := rv.Built(ctx, "ends", v.Version, v.Artifacts, nil); err != nil {
t.Fatal(err)
}
boundKey := versions.ReservedBoundKey("ends", "0.1")
// The holder refused a publish again within the bound (ADR 0674 §3): the bound's end keeps those words.
rv.unreleasedWords(ctx, v, "the holder refused the publish again: no space left")
if !rv.ended(ctx, purged{key: boundKey}) {
t.Fatal("the reservation's bound was not taken in")
}
if got := unreleased("ends"); !strings.Contains(got, "no space left") || strings.Contains(got, "nothing within") {
t.Errorf("at the bound's end, version-unreleased reads %q, want the holder's words it was left with", got)
}
// With none standing, the bound's end raises it, naming the artifact unpublished.
_ = fs.Clear(ctx, meshconditionsclient.ScopeModule, "ends", versions.VersionUnreleased, "")
rv.ended(ctx, purged{key: boundKey})
if got := unreleased("ends"); !strings.Contains(got, "ends:b unpublished") || !strings.Contains(got, "nothing within") {
t.Errorf("at the bound's end with none standing, version-unreleased reads %q, want nothing within naming ends:b", got)
}
// One whose every artifact is published is not left unmarked (1984/AC5): its bound's end raises nothing, and it waits for
// its version-released.
all := recordedLost("endsall", now.Add(-time.Minute), "a", "b")
if err := rv.Built(ctx, "endsall", all.Version, all.Artifacts, nil); err != nil {
t.Fatal(err)
}
if cur, _, _ := rv.r.Of(ctx, "endsall", all.Version); len(cur.Missing()) != 0 {
t.Fatalf("endsall: %v unpublished after the take-in, want every artifact published", cur.Missing())
}
rv.ended(ctx, purged{key: versions.ReservedBoundKey("endsall", "0.1")})
if got := unreleased("endsall"); got != "" {
t.Errorf("at the bound's end, a reservation whose every artifact is published raised %q, want no version-unreleased", got)
}
if cur, found, _ := rv.r.Of(ctx, "endsall", all.Version); !found || cur.BuiltAt.IsZero() {
t.Errorf("at the bound's end, the reservation of endsall %s stands no more, want it waiting for its version-released", all.Version)
}
})
}
// TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo: design 47 G A-455 — a build that reserves while the series is // TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo: design 47 G A-455 — a build that reserves while the series is
// reserved by an older build never released drops the older one's bound and finding and says so in the builder's journal; and // reserved by an older build never released drops the older one's bound and finding and says so in the builder's journal; and
// H-A-225 — the older build is withdrawn, so nothing publishes under the dropped number, while a re-run of the newer keeps it. // H-A-225 — the older build is withdrawn, so nothing publishes under the dropped number, while a re-run of the newer keeps it.
@@ -323,9 +607,7 @@ func TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo(t *testing.T)
call := func(string, any) (json.RawMessage, error) { call := func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
} }
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
nil, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
rv.filled.Store(true)
var withdrawn []string var withdrawn []string
rv.withdraw = func(module, fp, why string) { withdrawn = append(withdrawn, module+" "+fp+": "+why) } rv.withdraw = func(module, fp, why string) { withdrawn = append(withdrawn, module+" "+fp+": "+why) }
older, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: "fp-old"}) older, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: "fp-old"})
@@ -452,7 +734,7 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
} }
bounds := &boundsKV{keys: map[string]bool{}} bounds := &boundsKV{keys: map[string]bool{}}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return bounds }, rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return bounds },
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, t.Logf) &findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, t.Logf)
var said []meshbuilds.PackagePublished var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil } rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
var asked, ended []string var asked, ended []string
@@ -461,7 +743,6 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
rv.itemEnded = rv.released // a build withdrawn or superseded ends its publish item too (§793) rv.itemEnded = rv.released // a build withdrawn or superseded ends its publish item too (§793)
registry := []string{"0.1.37"} registry := []string{"0.1.37"}
rv.r.HeldNumbers = func(context.Context, string, string, []string) ([]string, error) { return registry, nil } rv.r.HeldNumbers = func(context.Context, string, string, []string) ([]string, error) { return registry, nil }
rv.filled.Store(true)
res, err := rv.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, versions.Source{Fingerprint: "fp1"}) res, err := rv.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, versions.Source{Fingerprint: "fp1"})
if err != nil || res.Version != "0.1.0" { if err != nil || res.Version != "0.1.0" {
t.Fatalf("reserved %q (%v)", res.Version, err) t.Fatalf("reserved %q (%v)", res.Version, err)
@@ -525,18 +806,34 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
} }
} }
// countedReserve counts the reads of reservation keys (two tokens). // countedReserve counts the reads of reservation keys (two tokens) and of the index beside them, and with writes the writes of
// each key (issue 1984 note 8).
type countedReserve struct { type countedReserve struct {
*memReserve *memReserve
reads int reads, indexReads int
writes map[string]int
} }
func (c *countedReserve) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) { func (c *countedReserve) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
if !strings.HasPrefix(key, "index.") { if !strings.HasPrefix(key, "index.") {
c.reads++ c.reads++
} else {
c.indexReads++
} }
return c.memReserve.Get(ctx, key) return c.memReserve.Get(ctx, key)
} }
func (c *countedReserve) Create(ctx context.Context, key string, v []byte) (uint64, error) {
if c.writes != nil {
c.writes[key]++
}
return c.memReserve.Create(ctx, key, v)
}
func (c *countedReserve) Update(ctx context.Context, key string, v []byte, rev uint64) (uint64, error) {
if c.writes != nil {
c.writes[key]++
}
return c.memReserve.Update(ctx, key, v, rev)
}
// TestAPublishedThatMarksNothingIsSaidFromWhatItRead: design 47 H H-A-280 — a published whose digest no reservation holds, at a // TestAPublishedThatMarksNothingIsSaidFromWhatItRead: design 47 H H-A-280 — a published whose digest no reservation holds, at a
// version many reservations share, reads only the unbuilt ones there, each once; its journal line is made from those reads with // version many reservations share, reads only the unbuilt ones there, each once; its journal line is made from those reads with
@@ -547,9 +844,8 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) } none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
var logs []string var logs []string
rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil, &findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now},
func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }) func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) })
rv.filled.Store(true)
for i := range 14 { for i := range 14 {
m := fmt.Sprintf("m%02d", i) m := fmt.Sprintf("m%02d", i)
res, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "fp" + m}) res, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "fp" + m})
@@ -629,6 +925,58 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
}) })
} }
// Design 47 H2 H-A-514 addenda: each event goes to the worker of the name it carries, so a slow handling of one name holds
// no other name's events, one name's events are handled in the order heard, and an event waiting in its worker's queue is
// said in progress at each tick, so the bus does not give it again.
func TestEventsAreHandledByAWorkerPerName(t *testing.T) {
pub := func(name, v string) *queuedEvent {
return &queuedEvent{wakeMsg: wakeMsg{subject: gopackageregistry.SubjectPublished, data: []byte(`{"name":"` + name + `","version":"` + v + `","digest":"sha256:aa"}`)}}
}
if got := eventKey(&pub("a", "1").wakeMsg); got != "name a" {
t.Errorf("a published's key is %q, want its name", got)
}
if got := eventKey(&wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"module":"m","version":"0.1.0"}`)}); got != "module m" {
t.Errorf("a version-released's key is %q, want its module", got)
}
if got := eventKey(&wakeMsg{subject: "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", data: []byte(`{}`)}); got != "" {
t.Errorf("an event naming no name has the key %q, want the shared worker's", got)
}
release := make(chan struct{})
handled := make(chan string, 4)
w := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) {
var o versions.Outcome
_ = json.Unmarshal(m.Data(), &o)
if o.Name == "a" && o.Version == "1" {
<-release
}
handled <- o.Name + "@" + o.Version
}}
a1, a2, a3, b1 := pub("a", "1"), pub("a", "2"), pub("a", "3"), pub("b", "1")
w.take(a1)
w.take(a2)
w.take(a3)
w.take(b1)
if got := <-handled; got != "b@1" {
t.Fatalf("handled %s first, want b's event while a's first one is slow", got)
}
close(release)
if got := []string{<-handled, <-handled, <-handled}; !slices.Equal(got, []string{"a@1", "a@2", "a@3"}) {
t.Errorf("a's events handled %v, want in the order heard", got)
}
// a's worker said its waiting events in progress at each end: a2 and a3 after a1, a3 again after a2.
if a1.progressed.Load() != 0 || a2.progressed.Load() != 1 || a3.progressed.Load() != 2 {
t.Errorf("in progress said %d, %d and %d times of a's events, want 0, 1 and 2", a1.progressed.Load(), a2.progressed.Load(), a3.progressed.Load())
}
}
// queuedEvent is an event of the builder's durable that counts its in-progress.
type queuedEvent struct {
wakeMsg
progressed atomic.Int32
}
func (m *queuedEvent) InProgress() error { m.progressed.Add(1); return nil }
// oneHandler is an event hub with one handler. // oneHandler is an event hub with one handler.
type oneHandler struct{ handle func(jetstream.Msg) } type oneHandler struct{ handle func(jetstream.Msg) }
@@ -178,4 +178,66 @@ func TestTheProcessAnswersReserved(t *testing.T) {
if _, err := drop("", json.RawMessage(`{"id":"ask-3"}`)); err == nil { if _, err := drop("", json.RawMessage(`{"id":"ask-3"}`)); err == nil {
t.Error("a drop with no why was taken") t.Error("a drop with no why was taken")
} }
// Design 47 H2 H-A-514: each ask's take and its ask-taken are its own worker's, started at the pull, so an ask whose
// ask-taken hangs holds neither the pull nor the next ask's ask-taken.
hang, release := make(chan struct{}), make(chan struct{})
saidTaken := make(chan string, 4)
slow := &stepQueue{node: "n1", builder: blockingBuilder{started: make(chan string, 2)}, taken: &takenFake{vals: map[string][]byte{}, ttls: map[string]time.Duration{}},
takenBound: 10 * time.Minute, inProgress: func() time.Duration { return 0 }, logf: t.Logf, now: time.Now, running: map[string]*runningAsk{},
say: func(_ context.Context, subject, _ string, _ any) error {
if subject == meshbuilds.SubjectAskTaken("ask-5") {
close(hang)
<-release
}
if strings.Contains(subject, "ask-taken") {
saidTaken <- subject
}
return nil
}}
pulled := make(chan struct{})
go func() {
slow.take(t.Context(), stepMsg("ask-5"))
<-hang
slow.take(t.Context(), stepMsg("ask-6"))
close(pulled)
}()
await(t, pulled, "the pull of ask-6 while ask-5's ask-taken hangs")
select {
case s := <-saidTaken:
if s != meshbuilds.SubjectAskTaken("ask-6") {
t.Errorf("said %s first, want ask-6's ask-taken", s)
}
case <-time.After(5 * time.Second):
t.Error("ask-6's ask-taken waited behind ask-5's")
}
close(release)
await(t, saidTaken, "ask-5's ask-taken once let go")
// The H-A-514 addendum: while an ask builds or its build waits for a package, the builder says the seat mesh-builds'
// step-progress of it at each tick of its minute clock, so the runner's bound of the ask is armed again.
tick := make(chan time.Time)
progressed := make(chan meshbuilds.StepProgressEvent, 1)
building := make(chan string, 1)
pq := &stepQueue{node: "n1", builder: blockingBuilder{started: building}, taken: &takenFake{vals: map[string][]byte{}, ttls: map[string]time.Duration{}},
takenBound: 10 * time.Minute, inProgress: func() time.Duration { return 0 }, logf: t.Logf, now: time.Now, running: map[string]*runningAsk{},
progress: func() (<-chan time.Time, func()) { return tick, func() {} },
say: func(_ context.Context, subject, _ string, body any) error {
if p, ok := body.(meshbuilds.StepProgressEvent); ok && subject == meshbuilds.SubjectStepProgress("n1") {
progressed <- p
}
return nil
}}
pq.take(t.Context(), stepMsg("ask-7"))
await(t, building, "the build of ask-7")
at := time.Date(2026, 11, 23, 2, 41, 0, 0, time.UTC)
tick <- at
select {
case p := <-progressed:
if p.Ask != "ask-7" || p.Asker != "main.1.m" || p.Phase != meshbuilds.StepProgressEventPhaseBuild || !p.At.Equal(at) {
t.Errorf("step-progress said %+v", p)
}
case <-time.After(5 * time.Second):
t.Error("no step-progress was said of ask-7 while it builds")
}
} }
@@ -4,9 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"strconv" "strconv"
"strings"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
@@ -44,10 +42,9 @@ var seatEvents = map[string]seatEvent{
npmpackageregistry.SubjectKept: {npmpackageregistry.Seat, npmpackageregistry.EventKept}, npmpackageregistry.SubjectKept: {npmpackageregistry.Seat, npmpackageregistry.EventKept},
} }
// seatHearer takes the registry seats' outcomes in: each moves a numbered version (versions.Numberer.Heard), and a // seatHearer takes the registry seats' outcomes in: the publishes' findings and the reservations hear them (design 47 G §369,
// `published` that wakes a name waiting on its floor looks at every module again. // A-415); the numbering from before G, which marked its state versions with them, is gone (design 47 H §756).
type seatHearer struct { type seatHearer struct {
n *versions.Numberer
b *build.Builder b *build.Builder
logf func(string, ...any) logf func(string, ...any)
// pub raises and clears the findings of a publish that ended badly; nil raises none. // pub raises and clears the findings of a publish that ended badly; nil raises none.
@@ -79,26 +76,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
if h.pub != nil { if h.pub != nil {
h.pub.read(ctx, se.seat) h.pub.read(ctx, se.seat)
} }
id := ""
if m.Headers() != nil {
id = m.Headers().Get("x-event-id")
}
wake, err := h.n.Heard(ctx, se.seat, se.event, id, o)
if errors.Is(err, versions.ErrNotNumbered) {
// The version is no entry of the state versions, design 51's numbering by name, which G keeps only until it is removed
// (§372); the reservation numbers a version (§369, §52) and takes the outcome in (A-415). Heard again it would stay
// unnumbered there, so it is taken, not left for the bus.
h.logf("%v in the state versions; the reservations take it (design 47 G §369, A-415)", err)
err = nil
}
if err != nil {
h.logf("%v; heard again (delivery %s)", err, deliveryOf(m))
if nakErr := m.Nak(); nakErr != nil {
h.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
}
givenUp(m, fmt.Sprintf("%s's %s of %s@%s", se.seat, se.event, o.Name, o.Version), err, h.logf)
return true
}
if h.pub != nil { if h.pub != nil {
h.pub.heard(ctx, se.seat, se.event, o) h.pub.heard(ctx, se.seat, se.event, o)
} }
@@ -115,10 +92,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
h.b.PackagePublished(o.Name, o.Version) h.b.PackagePublished(o.Name, o.Version)
} }
h.ack(m) h.ack(m)
if len(wake) > 0 {
h.logf("the floor of %s is asked again: %s said %s", strings.Join(wake, ", "), se.seat, se.event)
h.b.Reconsider(ctx)
}
return true return true
} }
@@ -150,7 +123,7 @@ func (h *seatHearer) ack(m jetstream.Msg) {
} }
} }
// kvKeeper is the state floor-waits as versions.FloorKeeper. // kvKeeper is a state of the builder as a keeper of keys: Put a key's value, Delete its key.
type kvKeeper struct { type kvKeeper struct {
ctx context.Context ctx context.Context
kv jetstream.KeyValue kv jetstream.KeyValue
@@ -168,27 +141,3 @@ func (k kvKeeper) Delete(key string) error {
} }
return err return err
} }
// heldFloorWaits are the waits floor-waits holds at the builder's start; a value that is no wait is said and left.
func heldFloorWaits(ctx context.Context, kv jetstream.KeyValue, logf func(string, ...any)) []versions.FloorWait {
l, err := kv.ListKeys(ctx)
if err != nil {
logf("%s cannot be listed, so a restart's waits are asked at their next claim: %v", versions.FloorWaitsState, err)
return nil
}
defer func() { _ = l.Stop() }()
var out []versions.FloorWait
for k := range l.Keys() {
e, err := kv.Get(ctx, k)
if err != nil {
continue
}
w, err := versions.DecodeFloorWait(e.Value())
if err != nil {
logf("%s.%s holds what is no floor wait, left: %v", versions.FloorWaitsState, k, err)
continue
}
out = append(out, w)
}
return out
}
@@ -66,6 +66,9 @@ type stepQueue struct {
takenBound time.Duration takenBound time.Duration
// inProgress is how often a running ask is said in progress: the seat definition's in-progress. // inProgress is how often a running ask is said in progress: the seat definition's in-progress.
inProgress func() time.Duration inProgress func() time.Duration
// progress is the clock step-progress is said on while an ask builds or its build waits for a package: every
// stepProgressEvery (design 47 H2 H-A-514 addendum); a test's when set.
progress func() (<-chan time.Time, func())
// say publishes a seat event of the builder (emitSeatEvent). // say publishes a seat event of the builder (emitSeatEvent).
say func(ctx context.Context, subject, id string, body any) error say func(ctx context.Context, subject, id string, body any) error
logf func(string, ...any) logf func(string, ...any)
@@ -75,6 +78,19 @@ type stepQueue struct {
running map[string]*runningAsk running map[string]*runningAsk
} }
// stepProgressEvery is how often the builder says step-progress of an ask it builds (design 47 H2 H-A-514 addendum): once a
// minute, as the seat mesh-wants' holder says its own.
const stepProgressEvery = time.Minute
// progressClock is the clock of step-progress: the test's, else a ticker of stepProgressEvery.
func (q *stepQueue) progressClock() (<-chan time.Time, func()) {
if q.progress != nil {
return q.progress()
}
t := time.NewTicker(stepProgressEvery)
return t.C, t.Stop
}
// runningAsk is an ask the builder took and builds now. // runningAsk is an ask the builder took and builds now.
type runningAsk struct { type runningAsk struct {
run meshbuilds.StepRun run meshbuilds.StepRun
@@ -91,10 +107,9 @@ func askIDOf(h nats.Header) string {
} }
// take handles one ask pulled from the queue: an ask that is no build step with an id is terminated, said; one this // take handles one ask pulled from the queue: an ask that is no build step with an id is terminated, said; one this
// builder runs already (handed again while it runs) is left to the run that holds it; any other is taken (ask-taken said // builder runs already (handed again while it runs) is left to the run that holds it; any other is held here and handed to
// the first time its id is taken) and built on its own goroutine, in progress while it runs, acknowledged once its end is // a worker of its own, started at once (design 47 H2 H-A-514): the pull never waits on a state call or a publish of an
// said. A repeat of an id taken before that runs here no longer (the builder started again) is answered as its builds // earlier ask, so each ask's ask-taken is said within its bound whatever the others do.
// stand now, read afresh by BuildStep (H-A-381 (1)): an entry built is answered built, never built twice.
func (q *stepQueue) take(ctx context.Context, m queueMsg) { func (q *stepQueue) take(ctx context.Context, m queueMsg) {
id := askIDOf(m.Headers()) id := askIDOf(m.Headers())
var run meshbuilds.StepRun var run meshbuilds.StepRun
@@ -110,36 +125,43 @@ func (q *stepQueue) take(ctx context.Context, m queueMsg) {
q.logf("the ask %s (%s) was handed again while it runs here: its run answers it", id, run.Pipeline) q.logf("the ask %s (%s) was handed again while it runs here: its run answers it", id, run.Pipeline)
return return
} }
// An ask dropped before it was pulled ends could-not-run naming the drop, with no build (H-A-404).
if d := q.droppedAsk(id); d != nil {
work, cancel := context.WithCancelCause(ctx)
cancel(d)
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
q.running[id] = ra
q.mu.Unlock()
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, run.Pipeline, d.Error())
go q.build(work, m, id, ra)
return
}
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
if err != nil {
q.mu.Unlock()
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, run.Pipeline, process.TakenState, err)
_ = m.Nak()
return
}
work, cancel := context.WithCancelCause(ctx) work, cancel := context.WithCancelCause(ctx)
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel} ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
q.running[id] = ra q.running[id] = ra
q.mu.Unlock() q.mu.Unlock()
go q.work(ctx, work, m, id, ra)
}
// work is one ask's worker (H-A-514): an ask dropped before it was pulled ends could-not-run naming the drop, with no build
// (H-A-404); any other is taken once by its id in the state taken (ask-taken said the first time it is taken) and built, in
// progress while it runs, acknowledged once its end is said. A repeat of an id taken before that runs here no longer (the
// builder started again) is answered as its builds stand now, read afresh by BuildStep (H-A-381 (1)): an entry built is
// answered built, never built twice. An ask the state taken refuses is let go and handed again.
func (q *stepQueue) work(ctx, work context.Context, m queueMsg, id string, ra *runningAsk) {
if d := q.droppedAsk(id); d != nil {
ra.cancel(d)
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, ra.run.Pipeline, d.Error())
q.build(work, m, id, ra)
return
}
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
if err != nil {
ra.cancel(nil)
q.mu.Lock()
delete(q.running, id)
q.mu.Unlock()
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, ra.run.Pipeline, process.TakenState, err)
_ = m.Nak()
return
}
if first { if first {
if err := q.say(ctx, meshbuilds.SubjectAskTaken(id), id+"-taken", meshbuilds.AskTakenEvent{Ask: id, Node: q.node, At: ra.taken.UTC()}); err != nil { if err := q.say(ctx, meshbuilds.SubjectAskTaken(id), id+"-taken", meshbuilds.AskTakenEvent{Ask: id, Node: q.node, At: ra.taken.UTC()}); err != nil {
q.logf("saying ask-taken of %s: %v", id, err) q.logf("saying ask-taken of %s: %v", id, err)
} }
} else { } else {
q.logf("the ask %s (%s) was taken before: it is answered as its builds stand now", id, run.Pipeline) q.logf("the ask %s (%s) was taken before: it is answered as its builds stand now", id, ra.run.Pipeline)
} }
go q.build(work, m, id, ra) q.build(work, m, id, ra)
} }
// build runs one taken ask to its end and says it. // build runs one taken ask to its end and says it.
@@ -157,6 +179,10 @@ func (q *stepQueue) build(ctx context.Context, m queueMsg, id string, ra *runnin
defer t.Stop() defer t.Stop()
tick = t.C tick = t.C
} }
// step-progress is said every minute while the step builds or waits for a package, so the asker's bound of the ask is
// armed again (design 47 H2 H-A-514 addendum).
progress, stop := q.progressClock()
defer stop()
done := make(chan meshbuilds.StepEnded, 1) done := make(chan meshbuilds.StepEnded, 1)
go func() { done <- q.builder.BuildStep(ctx, id, ra.run) }() go func() { done <- q.builder.BuildStep(ctx, id, ra.run) }()
var end meshbuilds.StepEnded var end meshbuilds.StepEnded
@@ -166,6 +192,11 @@ func (q *stepQueue) build(ctx context.Context, m queueMsg, id string, ra *runnin
waiting = false waiting = false
case <-tick: case <-tick:
_ = m.InProgress() _ = m.InProgress()
case at := <-progress:
p := meshbuilds.StepProgressEvent{Ask: id, Asker: ra.run.Pipeline, Phase: meshbuilds.StepProgressEventPhaseBuild, At: at.UTC()}
if err := q.say(ctx, meshbuilds.SubjectStepProgress(q.node), fmt.Sprintf("%s-progress-%d", id, at.UnixNano()), p); err != nil {
q.logf("saying step-progress of %s: %v", id, err)
}
} }
} }
if err := q.say(context.WithoutCancel(ctx), meshbuilds.SubjectStepEnded(q.node), id, end); err != nil { if err := q.say(context.WithoutCancel(ctx), meshbuilds.SubjectStepEnded(q.node), id, end); err != nil {
@@ -0,0 +1,50 @@
{
"module": "disk-load",
"version": "0.1",
"class": "leaf",
"tools": [
"disk_load",
"disk_top",
"disk_filesystems",
"disk_folders",
"disk_devices",
"cpu_top",
"disk_readings",
"disk_round",
"disk_measure"
],
"build": {
"artifacts": [
{
"name": "tools-go",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/disk-load",
"binary": "disk-load",
"loads": [
"disk-load"
]
},
{
"name": "diskreadings",
"kind": "package",
"language": "go",
"paths": [
"diskreadings"
],
"series": "0.1"
}
]
},
"state": [
"readings",
{
"name": "rounds",
"per-machine": true
}
],
"reads": [
"mesh-host.data"
]
}
@@ -4,43 +4,31 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"strings"
"time" "time"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-builder/internal/build"
"mesh-delivery-builder/internal/versions" "mesh-delivery-builder/internal/versions"
) )
// awaitedVersions is the state versions as versions.Store: bound once the bus holds it (the grants part makes it, issue // awaitedState is one of the builder's states as versions.Store: bound once the bus holds it (the grants part makes it,
// 1790); until then every use is an error, so a trunk build is built unnumbered and said (build.Builder.number). // issue 1790); until then every use is an error naming the state's bucket.
type awaitedVersions struct { type awaitedState struct {
b *process.AwaitedBucket b *process.AwaitedBucket
// bucket names the state in the error of one not on the bus yet; empty is the versions'.
bucket string bucket string
} }
var errVersionsMissing = errors.New("the state " + versions.State + " is not on the bus yet") func (s awaitedState) kv() (jetstream.KeyValue, error) {
func (s awaitedVersions) kv() (jetstream.KeyValue, error) {
if kv := s.b.KV(); kv != nil { if kv := s.b.KV(); kv != nil {
return kv, nil return kv, nil
} }
if s.bucket != "" { return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
}
return nil, errVersionsMissing
} }
func (s awaitedVersions) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) { func (s awaitedState) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
kv, err := s.kv() kv, err := s.kv()
if err != nil { if err != nil {
return nil, 0, false, err return nil, 0, false, err
@@ -62,7 +50,7 @@ func versionsConflict(err error) error {
return err return err
} }
func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (uint64, error) { func (s awaitedState) Create(ctx context.Context, key string, value []byte) (uint64, error) {
kv, err := s.kv() kv, err := s.kv()
if err != nil { if err != nil {
return 0, err return 0, err
@@ -71,7 +59,7 @@ func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (
return rev, versionsConflict(err) return rev, versionsConflict(err)
} }
func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) { func (s awaitedState) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
kv, err := s.kv() kv, err := s.kv()
if err != nil { if err != nil {
return 0, err return 0, err
@@ -80,7 +68,7 @@ func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, r
return rev, versionsConflict(err) return rev, versionsConflict(err)
} }
func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, error) { func (s awaitedState) KeysOf(ctx context.Context, filter string) ([]string, error) {
kv, err := s.kv() kv, err := s.kv()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -97,92 +85,6 @@ func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, e
return out, nil return out, nil
} }
// publishedVersionsVia asks the Go package registry seat's verb versions for one package path (design 47 H H-A-194): its
// versions, newest first.
func publishedVersionsVia(call toolCaller) func(context.Context, string) ([]string, error) {
return func(_ context.Context, path string) ([]string, error) {
raw, err := call("seat:"+gopackageregistry.Seat+"."+gopackageregistry.VerbVersions, gopackageregistry.VersionsInput{Name: path})
if err != nil {
return nil, err
}
var a gopackageregistry.VersionsAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", gopackageregistry.Seat, err)
}
var out []string
for _, v := range a.Versions {
if v.Version != "" {
out = append(out, v.Version)
}
}
return out, nil
}
}
// floorVia is the floor's three sources as calls of the builder's own account (design 51 *The floor*): the seat's verb
// versions, the seat git's tags and the requirements the catalog half's entries name (A-119). A call that fails is that source
// silent.
func floorVia(call toolCaller, requirements func(context.Context, string) ([]string, error)) versions.FloorSources {
return versions.FloorSources{
Seat: func(_ context.Context, seat, name string) ([]string, error) {
raw, err := call("seat:"+seat+".versions", map[string]any{"name": name})
if err != nil {
return nil, err
}
var a struct {
Versions []struct {
Version string `json:"version"`
} `json:"versions"`
}
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", seat, err)
}
var out []string
for _, v := range a.Versions {
if v.Version != "" {
out = append(out, v.Version)
}
}
return out, nil
},
Tags: func(ctx context.Context, repository, prefix string) ([]string, error) {
tags, _, err := tagsVia(call)(ctx, repository, prefix)
out := make([]string, 0, len(tags))
for _, t := range tags {
out = append(out, t.Tag)
}
return out, err
},
Requirements: requirements,
}
}
// tagsVia reads a repository's tags starting with prefix, each with the commit it names, through the seat git's verb tags,
// whichever module holds the seat (design 47 G §7, A-82), page by page; its answer is read tolerantly, form 2 naming each tag's
// commit (design 47 H2 §796, §780). away says the read met a transport fault or the error kind away (§776).
func tagsVia(call toolCaller) func(ctx context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
return func(_ context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
var out []gitseat.Tag
for page := int64(1); ; page++ {
raw, err := call("seat:"+gitseat.Seat+"."+gitseat.VerbTags, gitseat.TagsInput{Repository: repository, Prefix: prefix, Page: page})
if err != nil {
return nil, true, err
}
a, _, err := gitseat.DecodeTagsAnswer(raw)
if err != nil {
return nil, false, fmt.Errorf("the seat git's tags answered what is no list of tags: %w", err)
}
if a.Error != "" {
return nil, a.ErrorKind == gitseat.ErrorKindAway, fmt.Errorf("the seat git's tags: %s (%s)", a.Error, a.ErrorKind)
}
out = append(out, a.Tags...)
if !a.More {
return out, false, nil
}
}
}
}
// emitEvent says one of the builder's events, mesh.mod.<module>.event.<event>, with the SDK's envelope headers and id as // emitEvent says one of the builder's events, mesh.mod.<module>.event.<event>, with the SDK's envelope headers and id as
// the bus's dedup id. // the bus's dedup id.
func emitEvent(ctx context.Context, js jetstream.JetStream, cred process.Account, event, id string, body any) error { func emitEvent(ctx context.Context, js jetstream.JetStream, cred process.Account, event, id string, body any) error {
@@ -221,65 +123,3 @@ func emitSeatEvent(ctx context.Context, js jetstream.JetStream, cred process.Acc
_, err = js.PublishMsg(pub, msg, jetstream.WithMsgID(id)) _, err = js.PublishMsg(pub, msg, jetstream.WithMsgID(id))
return err return err
} }
// The events on the builder's consumer of EVENTS that wake a floor (design 51 *The floor*, DLV-B3b).
var (
// The indexer's take-in.taken, which the builder consumes in place of the retired manifest-accepted (design 47 H H-A-116).
takenInSubject = "mesh.mod.mesh-delivery-indexer.event.take-in.taken"
conditionClearedSubject = meshconditions.SubjectConditionCleared
)
// floorWake asks the floor of the names an event wakes again, by looking at every module again: a trunk build is
// numbered before its claim (build.Builder.number).
type floorWake struct {
b *build.Builder
waits *versions.FloorWaits
logf func(string, ...any)
}
// heard takes a message of the consumer in when it is one that wakes a floor, acknowledged, and answers whether it was.
func (f *floorWake) heard(ctx context.Context, m jetstream.Msg) bool {
switch m.Subject() {
case takenInSubject:
f.ack(m)
f.wake(ctx, versions.WakeTakenIn, "", "")
case conditionClearedSubject:
f.ack(m)
var e meshconditions.ConditionEvent
if err := json.Unmarshal(m.Data(), &e); err != nil {
f.logf("%s holds what is no condition, left: %v", m.Subject(), err)
return true
}
if e.Subject == nil {
return true
}
for _, module := range conditionModules(e.Subject.ID) {
f.wake(ctx, versions.WakeCleared, "", module)
}
default:
return false
}
return true
}
func (f *floorWake) ack(m jetstream.Msg) {
if err := m.Ack(); err != nil {
f.logf("acknowledging %s: %v", m.Subject(), err)
}
}
// wake looks at every module again when the event wakes a name, and says which.
func (f *floorWake) wake(ctx context.Context, kind, seat, module string) {
names := f.waits.Wake(kind, seat, module, "")
if len(names) == 0 {
return
}
f.logf("the floor of %s is asked again: %s", strings.Join(names, ", "), kind)
f.b.Reconsider(ctx)
}
// conditionModules are the tokens of a condition's subject id (`<node>/<module>`, `<module>.<check>`): a module named
// among them is the one whose condition cleared.
func conditionModules(id string) []string {
return strings.FieldsFunc(id, func(r rune) bool { return r == '/' || r == '.' || r == ':' })
}
@@ -19,6 +19,8 @@ import (
// `module` alone the module's keys newest first, at most MostBuilds, each with its fingerprint whole, its state, revision and // `module` alone the module's keys newest first, at most MostBuilds, each with its fingerprint whole, its state, revision and
// since when, its step and node, its error whole, event-builds and the open ask (§568), and `newest` naming each watched branch // since when, its step and node, its error whole, event-builds and the open ask (§568), and `newest` naming each watched branch
// whose newest catalog graph entry of the module names that fingerprint, read from the catalog half by the tools bundle. // whose newest catalog graph entry of the module names that fingerprint, read from the catalog half by the tools bundle.
// **Each key's time is its entry's own write time** (design 47 H2 H-A-487): the history of a key is read only for the one key a
// fingerprint names, when its entry does not say when it was written, and a listing cut at MostBuilds says so in its note.
// BuildTool is the builder's read tool of a module's build keys. // BuildTool is the builder's read tool of a module's build keys.
const BuildTool = "builder_build" const BuildTool = "builder_build"
@@ -56,14 +58,16 @@ type BuildAnswer struct {
Builds []BuildRow `json:"builds"` Builds []BuildRow `json:"builds"`
// Newest is the fingerprint of the module's newest catalog graph entry on each watched branch. // Newest is the fingerprint of the module's newest catalog graph entry on each watched branch.
Newest map[string]string `json:"newest-entries,omitempty"` Newest map[string]string `json:"newest-entries,omitempty"`
// Note says what no key shows: that none of the keys is the newest entry's, naming its fingerprint. // Note says what no key shows: that none of the keys is the newest entry's, naming its fingerprint, and that the listing
// was cut at MostBuilds (H-A-487).
Note string `json:"note,omitempty"` Note string `json:"note,omitempty"`
} }
// BuildReader reads what builder_build answers. // BuildReader reads what builder_build answers.
type BuildReader struct { type BuildReader struct {
Builds StateRead Builds StateRead
// Entry is a key's value with its revision and when it was written; nil leaves both out. // Entry is a key's value with its revision and when it was written, the entry's own write time (H-A-487); nil leaves both
// out. Builds.Written, the key's history, is read only for the key a fingerprint names when Entry says no time.
Entry func(key string) (json.RawMessage, uint64, time.Time, error) Entry func(key string) (json.RawMessage, uint64, time.Time, error)
// Asked is the builder's state asked, which holds the asks the operator was asked. // Asked is the builder's state asked, which holds the asks the operator was asked.
Asked StateRead Asked StateRead
@@ -96,6 +100,9 @@ func (r *BuildReader) Build(module, fingerprint string) (BuildAnswer, error) {
if raw == nil { if raw == nil {
continue continue
} }
if at.IsZero() && fingerprint != "" && r.Builds.Written != nil {
at = r.Builds.Written(key) // one key's history, never every key's (H-A-487)
}
v, err := builds.DecodeBuilderBuild(raw) v, err := builds.DecodeBuilderBuild(raw)
if err != nil { if err != nil {
return out, fmt.Errorf("%s holds what is not a build: %w", key, err) return out, fmt.Errorf("%s holds what is not a build: %w", key, err)
@@ -118,7 +125,9 @@ func (r *BuildReader) Build(module, fingerprint string) (BuildAnswer, error) {
} }
return rows[i].Key > rows[j].Key return rows[i].Key > rows[j].Key
}) })
var cut string
if len(rows) > MostBuilds { if len(rows) > MostBuilds {
cut = fmt.Sprintf("%d of %s's %d build keys are answered, the newest by write time; name a fingerprint for another", MostBuilds, module, len(rows))
rows = rows[:MostBuilds] rows = rows[:MostBuilds]
} }
asks := r.openAsks() asks := r.openAsks()
@@ -149,6 +158,9 @@ func (r *BuildReader) Build(module, fingerprint string) (BuildAnswer, error) {
out.Note = "no build key of " + module + " is the newest entry's: " + strings.Join(says, "; ") out.Note = "no build key of " + module + " is the newest entry's: " + strings.Join(says, "; ")
} }
} }
if cut != "" {
out.Note = strings.TrimPrefix(out.Note+"; "+cut, "; ")
}
out.Builds = append(out.Builds, rows...) out.Builds = append(out.Builds, rows...)
return out, nil return out, nil
} }
@@ -2,6 +2,7 @@ package build
import ( import (
"encoding/json" "encoding/json"
"fmt"
"sort" "sort"
"strings" "strings"
"testing" "testing"
@@ -66,6 +67,31 @@ func TestBuilderBuildAnswersAModulesKeysWhole(t *testing.T) {
if n, err := r.Build("m", ""); err != nil || !strings.Contains(n.Note, "no build key of m is the newest entry's") || !strings.Contains(n.Note, "main names src2:"+strings.Repeat("c", 64)) { if n, err := r.Build("m", ""); err != nil || !strings.Contains(n.Note, "no build key of m is the newest entry's") || !strings.Contains(n.Note, "main names src2:"+strings.Repeat("c", 64)) {
t.Errorf("a module none of whose keys the newest entry names: %+v, %v", n, err) t.Errorf("a module none of whose keys the newest entry names: %+v, %v", n, err)
} }
// H-A-487: a module of 100 keys is read by each entry's own write time, no key's history read, and the listing is cut at the
// 20 newest, saying so; a fingerprint's key with no time in its entry has its one history read.
many, at := map[string][]byte{}, map[string]time.Time{}
base := time.Date(2026, 11, 22, 20, 0, 0, 0, time.UTC)
for i := range 100 {
k, _ := builds.BuilderBuildKey("big", fmt.Sprintf("src2:%064x", i))
many[k], at[k] = done, base.Add(time.Duration(i)*time.Minute)
}
histories := 0
st := stateOf(many)
st.Written = func(string) time.Time { histories++; return base }
big := &BuildReader{Builds: st, Entry: func(k string) (json.RawMessage, uint64, time.Time, error) { return many[k], 1, at[k], nil }}
a, err = big.Build("big", "")
if err != nil || len(a.Builds) != MostBuilds || !a.Builds[0].Since.Equal(base.Add(99*time.Minute)) || histories != 0 ||
!strings.Contains(a.Note, "20 of big's 100 build keys are answered") {
t.Fatalf("100 keys: %d rows, newest %v, %d histories read, note %q; want the 20 newest, no history, the cut said", len(a.Builds), a.Builds[0].Since, histories, a.Note)
}
big.Entry = func(k string) (json.RawMessage, uint64, time.Time, error) { return many[k], 1, time.Time{}, nil }
if a, err := big.Build("big", ""); err != nil || len(a.Builds) != MostBuilds || histories != 0 {
t.Fatalf("100 keys with no time in their entries: %d rows (%v), %d histories read; want no history read for a listing", len(a.Builds), err, histories)
}
if one, err := big.Build("big", fmt.Sprintf("src2:%064x", 7)); err != nil || len(one.Builds) != 1 || !one.Builds[0].Since.Equal(base) || histories != 1 {
t.Errorf("one fingerprint with no time in its entry: %+v (%v), %d histories; want its one history read", one, err, histories)
}
} }
// Design 47 G §589: builder_stuck answers each key's fingerprint whole, as the build-input fingerprint the catalog graph entry carries it. // Design 47 G §589: builder_stuck answers each key's fingerprint whole, as the build-input fingerprint the catalog graph entry carries it.
@@ -170,6 +170,7 @@ func Unreferenced(b builds.BuilderBuild) bool {
// clause 2, ADR 0498 clauses 4 and 5) or for digests that differ (buildrun.DigestsDifferPrefix, clause 4), // clause 2, ADR 0498 clauses 4 and 5) or for digests that differ (buildrun.DigestsDifferPrefix, clause 4),
// which wait for another fingerprint, and one failed for want of an image builder (NoImageBuilderPrefix), which waits for // which wait for another fingerprint, and one failed for want of an image builder (NoImageBuilderPrefix), which waits for
// another fingerprint or a node that runs the image build module (ClaimOptions.ImageBuilder); // another fingerprint or a node that runs the image build module (ClaimOptions.ImageBuilder);
// - a failed key withdrawn (withdrawnPrefix) is final for its fingerprint, taken again only by a person's build again (H-A-489);
// - a key queued waiting for a package version (Waits) is claimed building as a new revision once that version is // - a key queued waiting for a package version (Waits) is claimed building as a new revision once that version is
// published (ClaimOptions.Published, ADR 0500 clause 6), and not before; // published (ClaimOptions.Published, ADR 0500 clause 6), and not before;
// - a key left queued or building by this builder is taken as it stands (ADR 0478 clause 5: a stopped builder takes its // - a key left queued or building by this builder is taken as it stands (ADR 0478 clause 5: a stopped builder takes its
@@ -229,6 +230,8 @@ func (c Claimer) Claim(ctx context.Context, module, fingerprint, manifest string
return nil, nil return nil, nil
case cur.State == builds.BuildFailed && (builds.FailedUntilChanged(cur.Error) || strings.HasPrefix(cur.Error, buildrun.DigestsDifferPrefix)): case cur.State == builds.BuildFailed && (builds.FailedUntilChanged(cur.Error) || strings.HasPrefix(cur.Error, buildrun.DigestsDifferPrefix)):
return nil, nil return nil, nil
case cur.State == builds.BuildFailed && strings.HasPrefix(cur.Error, withdrawnPrefix) && !opt.ByHand:
return nil, nil // withdrawn is final for its fingerprint: no look builds it again (H-A-489)
case cur.State == builds.BuildFailed && builds.FailedOnTransportFault(cur.Error) && !opt.ByHand && !opt.TakeOver && !opt.ByEvent: case cur.State == builds.BuildFailed && builds.FailedOnTransportFault(cur.Error) && !opt.ByHand && !opt.TakeOver && !opt.ByEvent:
return nil, nil return nil, nil
case cur.State == builds.BuildFailed && strings.HasPrefix(cur.Error, NoImageBuilderPrefix) && (opt.ImageBuilder == nil || !opt.ImageBuilder()): case cur.State == builds.BuildFailed && strings.HasPrefix(cur.Error, NoImageBuilderPrefix) && (opt.ImageBuilder == nil || !opt.ImageBuilder()):
@@ -23,11 +23,6 @@ func TestAnEntryOfTheCatalogHalfIsTheFormTheBuilderBuildsBy(t *testing.T) {
!reflect.DeepEqual(got.Inputs2.Paths, map[string]string{"a/b": "lib", "c": "lib"}) { !reflect.DeepEqual(got.Inputs2.Paths, map[string]string{"a/b": "lib", "c": "lib"}) {
t.Errorf("ModuleOf = %+v", got) t.Errorf("ModuleOf = %+v", got)
} }
// A module value carries no source stamp (design 47 H H-A-48): its claim is numbered per fingerprint, naming no source
// revision and no merge.
if c := ClaimOf("netcheck", got, Plan{}); c.Revision != "" || c.Merge != 0 || c.Fingerprint != "src2:f" {
t.Errorf("ClaimOf = %+v", c)
}
if bare := ModuleOf(meshcatalog.CatalogEntry{Module: "m"}); bare.Inputs2 != nil || bare.Fp2 != "" { if bare := ModuleOf(meshcatalog.CatalogEntry{Module: "m"}); bare.Inputs2 != nil || bare.Fp2 != "" {
t.Errorf("ModuleOf of an entry with none = %+v, want nothing set", bare) t.Errorf("ModuleOf of an entry with none = %+v, want nothing set", bare)
} }
@@ -10,9 +10,9 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
) )
// ADR 0593 §2 (F3): the imports a Go build module answers at a build's end reach the done key and the log's end entry, // B2/AC1 (design 47 H2 H-A-517, H-A-532 DQ-7): the imports a Go build module answers at a build's end reach neither the done
// where the indexer keeps them on the module. // key nor the log's end entry; the build module says them as imports-reported, its own build seat's event.
func importsABuildAnswersReachTheDoneKeyAndTheLog(t *testing.T) { func importsABuildAnswersReachNeitherTheDoneKeyNorTheLog(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/announce"} imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/announce"}
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step { r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -24,15 +24,32 @@ func importsABuildAnswersReachTheDoneKeyAndTheLog(t *testing.T) {
} }
return step return step
} }
var logged []builds.BuildLogEntry var logged [][]byte
var mu sync.Mutex var mu sync.Mutex
r.b.Node, r.b.Log = "novox", func(e builds.BuildLogEntry) { mu.Lock(); logged = append(logged, e); mu.Unlock() } r.b.Node, r.b.Log = "novox", func(e builds.BuildLogEntry) {
v := r.consider(t, "modules/m") raw, err := builds.EncodeBuildLogEntry(e)
if v.State != builds.BuildDone || strings.Join(v.Imports, ",") != strings.Join(imports, ",") { if err != nil {
t.Fatalf("done key %+v, want the imports", v) t.Errorf("a log entry does not encode: %v", err)
}
mu.Lock()
logged = append(logged, raw)
mu.Unlock()
} }
if len(logged) != 2 || strings.Join(logged[1].Imports, ",") != strings.Join(imports, ",") || len(logged[0].Imports) != 0 { if v := r.consider(t, "modules/m"); v.State != builds.BuildDone {
t.Fatalf("log %+v, want the imports on the end alone", logged) t.Fatalf("done key %+v, want it done", v)
}
if raw := string(r.st.vals[r.key]); strings.Contains(raw, `"imports"`) || strings.Contains(raw, "announce") {
t.Errorf("the done key %s carries the imports", raw)
}
mu.Lock()
defer mu.Unlock()
if len(logged) != 2 {
t.Fatalf("log %d entries, want the start and the end", len(logged))
}
for _, raw := range logged {
if strings.Contains(string(raw), `"imports"`) || strings.Contains(string(raw), "announce") {
t.Errorf("a log entry %s carries the imports", raw)
}
} }
} }
@@ -11,93 +11,10 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"mesh-delivery-builder/internal/versions" "mesh-delivery-builder/internal/versions"
) )
// Numbers numbers a trunk build at its claim (novox/hq design 51 *The versions*, ADR 0606, ADR 0617 §1) and records the
// digests it was built with. Nil numbers nothing.
type Numbers interface {
// done is the digests of the build's key when it is done already (versions.BuildClaim.Done), nil otherwise.
Number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, done map[string]string) (versions.Numbering, error)
Built(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, got versions.Numbering, made []builds.BuiltArtifact) error
}
// VersionNumbers is Numbers over the builder's state versions.
type VersionNumbers struct {
N *versions.Numberer
}
// ClaimOf is the claim a module value's trunk build is numbered by, per fingerprint: a module value carries no source stamp
// (design 47 H H-A-48), so the claim names no source revision and no merge.
func ClaimOf(module string, m meshcatalog.ModulesByModuleValue, plan Plan) versions.BuildClaim {
c := versions.BuildClaim{Module: module, Path: m.Path, Repository: trunk.RepositoryName(m.Repository), Fingerprint: m.Fp2,
Commit: m.Commit}
for _, t := range plan.Tasks {
c.Artifacts = append(c.Artifacts, versions.ClaimArtifact{Artifact: t.Artifact, Kind: t.Kind, Language: t.Language})
}
return c
}
func (v VersionNumbers) Number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, done map[string]string) (versions.Numbering, error) {
c := ClaimOf(module, m, plan)
c.Done = done
return v.N.Number(ctx, c)
}
func (v VersionNumbers) Built(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, got versions.Numbering, made []builds.BuiltArtifact) error {
digests := map[string]string{}
for _, a := range made {
digests[a.Name] = a.Digest
}
return v.N.Built(ctx, ClaimOf(module, m, plan), got, digests)
}
// number numbers a trunk build's artifacts before its claim: false
// when it waits for its floor (a package, design 51 *The floor*), and then nothing is claimed; the floor's wake looks at
// the module again.
func (b *Builder) number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan) (versions.Numbering, bool) {
if b.Numbers == nil {
return versions.Numbering{}, true
}
done := b.doneDigests(ctx, module, m.Fp2)
got, err := b.Numbers.Number(ctx, module, m, plan, done)
for _, s := range got.Said {
b.logf("%s at %s: %s", module, m.Fp2, s.Line)
// And in the build log (design 51 *The versions*: it says a version was kept, and why), between the build's start and end.
// A look at a key already done builds nothing and has no start or end: a version kept there says nothing new, and is
// not logged (each later look, a first view answered or a name heard, would add one).
if b.Log != nil && !(done != nil && s.Why == versions.SaidKept) {
b.Log(builds.BuildLogEntry{Event: builds.BuildSaidEvent, Module: module, FP: m.Fp2, Commit: m.Commit, Node: b.Node,
At: time.Now().UTC(), Line: s.Line, Why: s.Why})
}
}
if err != nil {
// Said, and built as before: an unnumbered build is published by its digest (ADR 0617 §1), numbered at its next look.
b.logf("%s at %s: %v", module, m.Fp2, fmt.Errorf("not numbered, the versions cannot be used: %w", err))
return versions.Numbering{}, true
}
if done != nil && len(got.Versions) > 0 && b.Reserved != nil {
// A late look numbered a done build: G §349 retires numbering at a look, so one with no reservation and no release is
// said aloud with the recovery that reserves it (A-455), never taken in silently.
_, reserved, rerr := b.Reserved.ReservedFor(ctx, module, m.Fp2)
released, derr := b.Reserved.ReleasedFor(ctx, module, m.Fp2)
if rerr == nil && derr == nil && !reserved && !released {
b.logf("%s at %s: a late look numbered this done build (%v) and no version is reserved for it: builder_reserve_done reserves one and queues its publish", module, m.Fp2, got.Versions)
}
}
if got.Refused != "" {
b.logf("%s at %s: %s", module, m.Fp2, got.Refused)
return got, true
}
if got.Wait != "" {
b.logf("%s at %s is not built yet: %s", module, m.Fp2, got.Wait)
return got, false
}
return got, true
}
// doneDigests are the digests of a trunk build's key by artifact when the key is done, nil otherwise or when it cannot be // doneDigests are the digests of a trunk build's key by artifact when the key is done, nil otherwise or when it cannot be
// read: a look at a done build numbers what it left unnumbered with them (versions.BuildClaim.Done). // read: a look at a done build numbers what it left unnumbered with them (versions.BuildClaim.Done).
func (b *Builder) doneDigests(ctx context.Context, module, fp string) map[string]string { func (b *Builder) doneDigests(ctx context.Context, module, fp string) map[string]string {
@@ -106,11 +23,19 @@ func (b *Builder) doneDigests(ctx context.Context, module, fp string) map[string
return nil return nil
} }
raw, _, found, err := b.Claimer.Store.Get(ctx, key) raw, _, found, err := b.Claimer.Store.Get(ctx, key)
if err != nil || !found { if err != nil {
b.logf("%s: the build key cannot be read, so it is taken as not done: %v", key, err)
return nil
}
if !found {
return nil return nil
} }
cur, err := builds.DecodeBuilderBuild(raw) cur, err := builds.DecodeBuilderBuild(raw)
if err != nil || cur.State != builds.BuildDone { if err != nil {
b.logf("%s: the build key holds what is no build, so it is taken as not done: %v", key, err)
return nil
}
if cur.State != builds.BuildDone {
return nil return nil
} }
out := map[string]string{} out := map[string]string{}
@@ -122,9 +47,67 @@ func (b *Builder) doneDigests(ctx context.Context, module, fp string) map[string
return out return out
} }
// PackageNamed looks at a module again when the indexer's packages state names a name for one of its packages // DefaultRecordBound is the bound of the record of a reservation's digests, its setting record-bound-seconds' default (design 47
// (versions.NamedModule): a done trunk build that left the package unnumbered, its name not known at its claim, is // H2 H-A-492).
// numbered then with the done build's digests, and version.numbered says them for its build module's late publish. const DefaultRecordBound = time.Minute
// recordContext is the context a reservation's digests are recorded under: ctx's values with no cancel of its own, bounded by
// RecordBound (design 47 H2 H-A-492), so a takeover or an end cancelling the build cannot cancel the record.
func (b *Builder) recordContext(ctx context.Context) (context.Context, context.CancelFunc) {
bound := b.RecordBound
if bound <= 0 {
bound = DefaultRecordBound
}
return context.WithTimeout(context.WithoutCancel(ctx), bound)
}
// RecordAgain records the digests of fp's done build under its standing reservation when its end did not record them all (design
// 47 H2 H-A-492): at the builder's look of the key and at its start (when says which), said each time. A reservation whose build
// ended recorded is handed to Built all the same, with the digests it holds, so its holder takes its state in (its bound, the
// published kept on it) whether or not the record before ended (issue 1984 note 8, 1984/AC5). It answers the version recorded, ""
// when nothing was to be recorded: the key is not done, no reservation stands for fp, or it is recorded already.
func (b *Builder) RecordAgain(ctx context.Context, module, fp, when string) (string, error) {
b.init()
if b.Reserved == nil {
return "", nil
}
digests := b.doneDigests(ctx, module, fp)
if digests == nil {
return "", nil
}
res, ok, err := b.Reserved.ReservedFor(ctx, module, fp)
if err != nil {
return "", fmt.Errorf("%s at %s: whether its done build's digests are recorded cannot be read %s: %w", module, fp, when, err)
}
if !ok || len(res.Artifacts) == 0 || versions.NotStanding(res, true) != "" {
return "", nil
}
rec, stop := b.recordContext(ctx)
defer stop()
if !res.BuiltAt.IsZero() {
if err := b.Reserved.Built(rec, module, res.Version, res.Artifacts, nil); err != nil {
return "", fmt.Errorf("%s at %s: the recorded build of %s is not taken in %s: %w", module, fp, res.Version, when, err)
}
return "", nil
}
refs := map[string]string{}
for ref := range res.Artifacts {
_, artifact, _ := strings.Cut(ref, ":")
d, have := digests[artifact]
if !have {
return "", fmt.Errorf("%s at %s: the digests of %s are not recorded, and the done key holds no digest of %s to record %s", module, fp, res.Version, ref, when)
}
refs[ref] = d
}
if err := b.Reserved.Built(rec, module, res.Version, refs, nil); err != nil {
return "", fmt.Errorf("%s at %s: the digests of %s are not recorded %s either: %w", module, fp, res.Version, when, err)
}
b.logf("%s at %s: the digests of %s were not recorded at its build's end: recorded %s from the done key", module, fp, res.Version, when)
return res.Version, nil
}
// PackageNamed looks at a module again when the catalog half's entry of it names a package's name in its ecosystem
// (design 47 G §348): a done build is looked at and nothing is built again.
func (b *Builder) PackageNamed(ctx context.Context, module string) { func (b *Builder) PackageNamed(ctx context.Context, module string) {
b.init() b.init()
b.mu.Lock() b.mu.Lock()
@@ -138,8 +121,6 @@ func (b *Builder) PackageNamed(ctx context.Context, module string) {
// Reservations reserves the version of a trunk build at its start and records each artifact's digest (design 47 G §369). // Reservations reserves the version of a trunk build at its start and records each artifact's digest (design 47 G §369).
// Nil reserves nothing. // Nil reserves nothing.
type Reservations interface { type Reservations interface {
// Filled says the catalog said versions-filled: nothing is reserved before it.
Filled() bool
// Reserve reserves module's next version in series for the artifacts (their references, <module>:<artifact>). // Reserve reserves module's next version in series for the artifacts (their references, <module>:<artifact>).
Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error)
// Built records the digests of the artifacts built under the reserved version, by reference, and what each resolved and was // Built records the digests of the artifacts built under the reserved version, by reference, and what each resolved and was
@@ -152,6 +133,9 @@ type Reservations interface {
// TakenOver is the reservation of module's series that took the series over from the build of fingerprint, whose number // TakenOver is the reservation of module's series that took the series over from the build of fingerprint, whose number
// it keeps withdrawn (design 47 H H-A-226), and whether one does (H-A-244). // it keeps withdrawn (design 47 H H-A-226), and whether one does (H-A-244).
TakenOver(ctx context.Context, module, fingerprint string) (versions.ReservedVersion, bool, error) TakenOver(ctx context.Context, module, fingerprint string) (versions.ReservedVersion, bool, error)
// VersionAt is the version module's artifact is published at from the source revision of branch: its reservation of that
// origin with the artifact published, else its release recorded at that source revision (design 47 H2 H-A-547 (3), H-A-551).
VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error)
} }
// reserves says whether a look at a trunk build is one that reserves: the build has a series of the form MAJOR.MINOR // reserves says whether a look at a trunk build is one that reserves: the build has a series of the form MAJOR.MINOR
@@ -173,23 +157,6 @@ func (b *Builder) reservesVersion(plan Plan) bool {
return len(plan.Tasks) > 0 && strings.Count(plan.Series, ".") == 1 return len(plan.Tasks) > 0 && strings.Count(plan.Series, ".") == 1
} }
// waitFill holds a build that would reserve until the catalog says versions-filled, saying wait-held naming the fill once
// (design 47 G §369, §372). It answers whether the build waits.
func (b *Builder) waitFill(module string, m meshcatalog.ModulesByModuleValue) bool {
if b.Reserved.Filled() {
return false
}
if _, said := b.fillWaits.LoadOrStore(module+"."+m.Fp2, true); !said {
line := module + " at " + m.Fp2 + " is not built yet: wait-held, the catalog has not said versions-filled, and nothing is reserved before it"
b.logf("%s", line)
if b.Log != nil {
b.Log(builds.BuildLogEntry{Event: builds.BuildSaidEvent, Module: module, FP: m.Fp2, Commit: m.Commit, Node: b.Node,
At: time.Now().UTC(), Line: line, Why: "wait-held"})
}
}
return true
}
// reserve reserves the version of the build that starts; a reservation that cannot be made is said and the build goes on // reserve reserves the version of the build that starts; a reservation that cannot be made is said and the build goes on
// unreserved: the caller fails the key, which a look takes again (A-490). // unreserved: the caller fails the key, which a look takes again (A-490).
func (b *Builder) reserve(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, o Origin, rebuild bool) (versions.ReservedVersion, bool) { func (b *Builder) reserve(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, o Origin, rebuild bool) (versions.ReservedVersion, bool) {
@@ -199,8 +166,8 @@ func (b *Builder) reserve(ctx context.Context, module string, m meshcatalog.Modu
} }
src := versions.Source{Repository: m.Repository, Commit: m.Commit, Fingerprint: m.Fp2, Branch: o.Branch, Revision: o.Source, CatalogRevision: o.Revision, Rebuild: rebuild} src := versions.Source{Repository: m.Repository, Commit: m.Commit, Fingerprint: m.Fp2, Branch: o.Branch, Revision: o.Source, CatalogRevision: o.Revision, Rebuild: rebuild}
for _, t := range plan.Tasks { for _, t := range plan.Tasks {
if t.Kind == catalogue.ArtifactPackage && t.Language == "go" && !src.GoPackage { if t.Kind == catalogue.ArtifactUpstream {
src.GoPackage, src.GoArtifact = true, t.Artifact // its module path names its tag's directory (design 47 H2 §796) src.Upstream = append(src.Upstream, module+":"+t.Artifact) // copied by its pin, never awaited (H-A-486)
} }
} }
res, err := b.Reserved.Reserve(ctx, module, plan.Series, refs, src) res, err := b.Reserved.Reserve(ctx, module, plan.Series, refs, src)
@@ -258,9 +225,6 @@ func (b *Builder) ReserveDone(ctx context.Context, module, fp string) (versions.
} else if ok { } else if ok {
return versions.ReservedVersion{}, fmt.Errorf("%s at %s holds the reservation of %s already", module, fp, cur.Version) return versions.ReservedVersion{}, fmt.Errorf("%s at %s holds the reservation of %s already", module, fp, cur.Version)
} }
if !b.Reserved.Filled() {
return versions.ReservedVersion{}, versions.ErrNotFilled
}
res, ok := b.reserve(ctx, module, m, plan, b.originOf(key), false) res, ok := b.reserve(ctx, module, m, plan, b.originOf(key), false)
if !ok { if !ok {
return versions.ReservedVersion{}, fmt.Errorf("no version could be reserved for %s at %s (the builder's journal says why)", module, fp) return versions.ReservedVersion{}, fmt.Errorf("no version could be reserved for %s at %s (the builder's journal says why)", module, fp)
@@ -8,6 +8,7 @@ import (
"reflect" "reflect"
"slices" "slices"
"strings" "strings"
"sync"
"testing" "testing"
"time" "time"
@@ -22,7 +23,6 @@ import (
// fakeReservations answers a fill and keeps what the builder reserved and recorded. // fakeReservations answers a fill and keeps what the builder reserved and recorded.
type fakeReservations struct { type fakeReservations struct {
filled bool
released map[string]bool released map[string]bool
reserved [][]string reserved [][]string
series []string series []string
@@ -32,6 +32,27 @@ type fakeReservations struct {
next string // the version Reserve answers when set, else the series' .5 next string // the version Reserve answers when set, else the series' .5
fail error // the reservation cannot be made (the catalog's versions cannot be read) fail error // the reservation cannot be made (the catalog's versions cannot be read)
tookBy map[string]versions.ReservedVersion // by fingerprint, the reservation that took its series over (H-A-244) tookBy map[string]versions.ReservedVersion // by fingerprint, the reservation that took its series over (H-A-244)
held map[string]versions.ReservedVersion // by fingerprint, the reservation ReservedFor answers as it stands (H-A-492)
lost error // the record of the digests fails, as a store refusing it would
atMu sync.Mutex
at map[string]string // by "<module>:<artifact>@<branch>.<source>", the version VersionAt answers (H-A-547 (3))
}
func (f *fakeReservations) VersionAt(_ context.Context, module, artifact, branch string, source int64) (string, bool, error) {
f.atMu.Lock()
defer f.atMu.Unlock()
v, ok := f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)]
return v, ok, nil
}
// publishAt makes VersionAt answer version for module's artifact at the origin branch and source.
func (f *fakeReservations) publishAt(module, artifact, branch string, source int64, version string) {
f.atMu.Lock()
defer f.atMu.Unlock()
if f.at == nil {
f.at = map[string]string{}
}
f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)] = version
} }
func (f *fakeReservations) TakenOver(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) { func (f *fakeReservations) TakenOver(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) {
@@ -43,9 +64,10 @@ func (f *fakeReservations) ReleasedFor(_ context.Context, _, fp string) (bool, e
return f.released[fp], nil return f.released[fp], nil
} }
func (f *fakeReservations) Filled() bool { return f.filled }
func (f *fakeReservations) ReservedFor(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) { func (f *fakeReservations) ReservedFor(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) {
if v, ok := f.held[fp]; ok {
return v, true, nil
}
for _, s := range f.sources { for _, s := range f.sources {
if s.Fingerprint == fp { if s.Fingerprint == fp {
return versions.ReservedVersion{Version: "held"}, true, nil return versions.ReservedVersion{Version: "held"}, true, nil
@@ -65,7 +87,13 @@ func (f *fakeReservations) Reserve(_ context.Context, module, series string, art
return versions.ReservedVersion{Module: module, Series: series, Version: series + ".5"}, nil return versions.ReservedVersion{Module: module, Series: series, Version: series + ".5"}, nil
} }
func (f *fakeReservations) Built(_ context.Context, _, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) error { func (f *fakeReservations) Built(ctx context.Context, _, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) error {
if err := ctx.Err(); err != nil {
return err // the state's write runs under ctx: a cancelled one records nothing
}
if f.lost != nil {
return f.lost
}
f.deps = deps f.deps = deps
f.built = map[string]string{version: ""} f.built = map[string]string{version: ""}
for ref, d := range digests { for ref, d := range digests {
@@ -74,8 +102,8 @@ func (f *fakeReservations) Built(_ context.Context, _, version string, digests m
return nil return nil
} }
// TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled: design 47 G §369, §372 (test 102) — nothing is reserved before // TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled: design 47 G §369 (test 102), H2 H-A-552 — the build waits for no
// versions-filled and the build waits saying wait-held naming the fill; after it the build reserves one version in the // fill and says no wait-held: it reserves one version in the
// manifest's MAJOR.MINOR for its artifacts and records their digests; a done key reserves nothing again; a manifest whose // manifest's MAJOR.MINOR for its artifacts and records their digests; a done key reserves nothing again; a manifest whose
// version is no MAJOR.MINOR reserves nothing. // version is no MAJOR.MINOR reserves nothing.
func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) { func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
@@ -86,22 +114,6 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
var said []builds.BuildLogEntry var said []builds.BuildLogEntry
r.b.Log = func(e builds.BuildLogEntry) { said = append(said, e) } r.b.Log = func(e builds.BuildLogEntry) { said = append(said, e) }
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
if _, ok := r.st.vals[r.key]; ok || len(res.reserved) != 0 {
t.Fatalf("before versions-filled the build was claimed (%v) or reserved %v", ok, res.reserved)
}
var waits []string
for _, e := range said {
if e.Event == builds.BuildSaidEvent && e.Why == "wait-held" {
waits = append(waits, e.Line)
}
}
if len(waits) != 1 || !slices.ContainsFunc(waits, func(l string) bool { return strings.Contains(l, "versions-filled") }) {
t.Fatalf("wait-held lines = %q, want one naming versions-filled", waits)
}
res.filled = true
// Design 47 G §573: the build's ask carries the reserved version. // Design 47 G §573: the build's ask carries the reserved version.
var askedVersions []string var askedVersions []string
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step { r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -115,9 +127,21 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
if v.State != builds.BuildDone || len(res.reserved) != 1 || !slices.Equal(res.reserved[0], []string{"m:tool"}) || res.series[0] != "0.1" { if v.State != builds.BuildDone || len(res.reserved) != 1 || !slices.Equal(res.reserved[0], []string{"m:tool"}) || res.series[0] != "0.1" {
t.Fatalf("build %+v reserved %v in %v, want done and one reservation of m:tool in 0.1", v.State, res.reserved, res.series) t.Fatalf("build %+v reserved %v in %v, want done and one reservation of m:tool in 0.1", v.State, res.reserved, res.series)
} }
for _, e := range said {
if e.Event == builds.BuildSaidEvent && e.Why == "wait-held" {
t.Errorf("the build said wait-held %q, want no wait for a fill (H-A-552)", e.Line)
}
}
if res.built["m:tool"] != digest || len(res.built) != 2 { if res.built["m:tool"] != digest || len(res.built) != 2 {
t.Errorf("recorded %v, want the digest of m:tool under the reserved version", res.built) t.Errorf("recorded %v, want the digest of m:tool under the reserved version", res.built)
} }
// H-A-486: an upstream artifact is reserved for the record and named as upstream, so its publish is never awaited.
up := &fakeReservations{}
plan := Plan{Series: "0.1", Tasks: []Task{{Artifact: "server", Kind: catalogue.ArtifactUpstream}, {Artifact: "tools", Kind: catalogue.ArtifactBundle}}}
if _, ok := (&Builder{Reserved: up}).reserve(context.Background(), "nats", meshcatalog.ModulesByModuleValue{Fp2: "f"}, plan, Origin{}, false); !ok ||
!slices.Equal(up.reserved[0], []string{"nats:server", "nats:tools"}) || !slices.Equal(up.sources[0].Upstream, []string{"nats:server"}) {
t.Errorf("an upstream artifact reserved %v from %+v, want both refs reserved and nats:server named upstream", up.reserved, up.sources)
}
r.consider(t, "modules/m") r.consider(t, "modules/m")
if len(res.reserved) != 1 { if len(res.reserved) != 1 {
t.Errorf("a done key reserved again: %v", res.reserved) t.Errorf("a done key reserved again: %v", res.reserved)
@@ -125,7 +149,7 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
// A manifest whose version is no MAJOR.MINOR reserves nothing and is built as before. // A manifest whose version is no MAJOR.MINOR reserves nothing and is built as before.
r2 := newRig(t, goBundle) r2 := newRig(t, goBundle)
res2 := &fakeReservations{filled: true} res2 := &fakeReservations{}
r2.b.Reserved = res2 r2.b.Reserved = res2
var unversioned []string var unversioned []string
r2.asks.Answer = func(a buildstep.StepAsk) buildstep.Step { r2.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -146,6 +170,102 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
} }
} }
// TestAVersionsDigestsAreRecordedUnderTheBuildersOwnBound: design 47 H2 H-A-492 — the record of a reservation's digests after a
// build ends runs under the builder's own bound, so a build context cancelled at its end still records; a done build whose
// digests are not recorded is recorded at the builder's next look, said.
func TestAVersionsDigestsAreRecordedUnderTheBuildersOwnBound(t *testing.T) {
manifest := catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
t.Run("a build's context cancelled at its end still records", func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = manifest
res := &fakeReservations{}
r.b.Reserved = res
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r.b.Ended = func(context.Context, string) { cancel() } // a takeover or the builder's end, once the key is written
r.b.Module(ctx, "m", moduleValue(t, "modules/m"))
r.b.Wait()
if v := valueOf(t, r.st, r.key); v.State != builds.BuildDone {
t.Fatalf("build = %+v, want done", v)
}
if res.built["m:tool"] != digest {
t.Errorf("recorded %v, want the digest of m:tool under 0.1.5 though the build's context ended", res.built)
}
})
t.Run("the record's bound is the setting record-bound-seconds, never the build's", func(t *testing.T) {
build, cancel := context.WithCancel(context.Background())
cancel()
for _, c := range []struct {
bound, want time.Duration
}{{0, DefaultRecordBound}, {5 * time.Second, 5 * time.Second}} {
rec, stop := (&Builder{RecordBound: c.bound}).recordContext(build)
deadline, has := rec.Deadline()
stop()
if left := time.Until(deadline); !has || left > c.want || left < c.want-time.Second {
t.Errorf("RecordBound %v: the record's context has deadline %v (%v left, %v), want %v left of its own", c.bound, deadline, left, has, c.want)
}
}
rec, stop := (&Builder{}).recordContext(build)
defer stop()
if rec.Err() != nil {
t.Errorf("the record's context ended with the build's: %v", rec.Err())
}
})
t.Run("a build key that cannot be read is said, not taken silently", func(t *testing.T) {
var journal []string
b := &Builder{Claimer: Claimer{Store: unreadable{newMem()}}, Logf: func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }}
if d := b.doneDigests(context.Background(), "m", fp1); d != nil {
t.Errorf("an unreadable key answered digests %v", d)
}
if !slices.ContainsFunc(journal, func(l string) bool {
return strings.Contains(l, "cannot be read") && strings.Contains(l, "bus timeout")
}) {
t.Errorf("journal %q, want a line saying the build key cannot be read, with why", journal)
}
})
t.Run("a done key whose digests are not recorded is recorded at the next look", func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = manifest
res := &fakeReservations{lost: errors.New("context canceled")}
r.b.Reserved = res
var journal []string
r.b.Logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
if v := r.consider(t, "modules/m"); v.State != builds.BuildDone || res.built != nil {
t.Fatalf("build %s recorded %v, want done and nothing recorded", v.State, res.built)
}
res.lost = nil
res.held = map[string]versions.ReservedVersion{fp1: {Module: "m", Series: "0.1", Version: "0.1.5", Fingerprint: fp1, Artifacts: map[string]string{"m:tool": ""}}}
r.consider(t, "modules/m")
if res.built["m:tool"] != digest || len(res.built) != 2 {
t.Errorf("recorded %v at the next look, want the done key's digest of m:tool under 0.1.5", res.built)
}
if !slices.ContainsFunc(journal, func(l string) bool {
return strings.Contains(l, "0.1.5 were not recorded") && strings.Contains(l, "recorded at a look")
}) {
t.Errorf("journal %q, want a line saying 0.1.5's digests were recorded at a look", journal)
}
// Issue 1984 note 8, 1984/AC5: a reservation whose build ended recorded is handed to Built at every look with the digests it
// holds, nothing recorded anew, so its holder takes its state in (the published kept on it, its bound) whether or not the
// record before ended; the journal says no record.
res.built, journal = nil, nil
res.held[fp1] = versions.ReservedVersion{Module: "m", Series: "0.1", Version: "0.1.5", Fingerprint: fp1, Artifacts: map[string]string{"m:tool": "sha256:recorded"}, BuiltAt: time.Unix(1, 0)}
r.consider(t, "modules/m")
if res.built["m:tool"] != "sha256:recorded" || len(res.built) != 2 {
t.Errorf("a recorded reservation at a look was given to Built as %v, want its recorded digest of m:tool under 0.1.5 (1984/AC5)", res.built)
}
if slices.ContainsFunc(journal, func(l string) bool { return strings.Contains(l, "were not recorded") }) {
t.Errorf("journal %q: a recorded reservation was said recorded again", journal)
}
})
}
// unreadable is a builds bucket whose reads fail, as one on a bus that does not answer.
type unreadable struct{ *memStore }
func (unreadable) Get(context.Context, string) ([]byte, uint64, bool, error) {
return nil, 0, false, errors.New("bus timeout")
}
// TestADropOfAReservationIsAReasksValueOfItsOwnKey: design 47 G §369 — builder_reserved_drop asks the builder through // TestADropOfAReservationIsAReasksValueOfItsOwnKey: design 47 G §369 — builder_reserved_drop asks the builder through
// reasks, under a key of the reservation (never a build key), refusing a module with no MAJOR.MINOR or no why. // reasks, under a key of the reservation (never a build key), refusing a module with no MAJOR.MINOR or no why.
func TestADropOfAReservationIsAReasksValueOfItsOwnKey(t *testing.T) { func TestADropOfAReservationIsAReasksValueOfItsOwnKey(t *testing.T) {
@@ -180,7 +300,7 @@ func TestOnlyABuildOfTheFirstWatchedBranchReservesAndItCarriesItsCatalogRevision
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true} res := &fakeReservations{}
r.b.Reserved = res r.b.Reserved = res
r.b.Entry(context.Background(), c.origin, meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m", r.b.Entry(context.Background(), c.origin, meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m",
Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1, ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}}) Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1, ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}})
@@ -201,7 +321,7 @@ func TestOnlyABuildOfTheFirstWatchedBranchReservesAndItCarriesItsCatalogRevision
func TestAReservedBuildKeepsWhatItsStepResolvedAndWasBuiltWith(t *testing.T) { func TestAReservedBuildKeepsWhatItsStepResolvedAndWasBuiltWith(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true} res := &fakeReservations{}
r.b.Reserved = res r.b.Reserved = res
var journal []string var journal []string
r.b.Logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) } r.b.Logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
@@ -236,7 +356,7 @@ func TestAReservedBuildKeepsWhatItsStepResolvedAndWasBuiltWith(t *testing.T) {
// TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion: design 47 G §370 — a module whose one artifact is // TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion: design 47 G §370 — a module whose one artifact is
// a Go package (mesh-wireguard's go-overlay) is planned on the Go build seat, its ask carries the reserved version and names // a Go package (mesh-wireguard's go-overlay) is planned on the Go build seat, its ask carries the reserved version and names
// the seat go-package-registry the package is published and tagged through, and the build is done; a build reserving none // the seat go-package-registry the package is published through, and the build is done; a build reserving none
// names no seat. // names no seat.
func TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion(t *testing.T) { func TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion(t *testing.T) {
goPackage := catalogue.Artifact{Name: "go-overlay", Kind: catalogue.ArtifactPackage, Language: "go", Paths: []string{"go"}} goPackage := catalogue.Artifact{Name: "go-overlay", Kind: catalogue.ArtifactPackage, Language: "go", Paths: []string{"go"}}
@@ -249,7 +369,7 @@ func TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion(t *t
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
r := newRig(t, goPackage) r := newRig(t, goPackage)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.series, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goPackage}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.series, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goPackage}}}
res := &fakeReservations{filled: true} res := &fakeReservations{}
r.b.Reserved = res r.b.Reserved = res
r.bm.packages["go-overlay"] = "git.novox.be/novox/mesh-networking/go@v0.1.5" // the Go build module's published reference r.bm.packages["go-overlay"] = "git.novox.be/novox/mesh-networking/go@v0.1.5" // the Go build module's published reference
var asked []buildstep.StepAsk var asked []buildstep.StepAsk
@@ -265,10 +385,6 @@ func TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion(t *t
len(asked[0].Build.Artifacts) != 1 || asked[0].Build.Artifacts[0] != (buildstep.AskArtifact{Artifact: "go-overlay", Seat: c.seat}) { len(asked[0].Build.Artifacts) != 1 || asked[0].Build.Artifacts[0] != (buildstep.AskArtifact{Artifact: "go-overlay", Seat: c.seat}) {
t.Fatalf("asks %+v, want one Go ask with version %q naming go-overlay on seat %q", asked, c.version, c.seat) t.Fatalf("asks %+v, want one Go ask with version %q naming go-overlay on seat %q", asked, c.version, c.seat)
} }
// Design 47 H2 §796: the reservation names the Go package's artifact, whose module path names its tag's directory.
if c.version != "" && (len(res.sources) != 1 || !res.sources[0].GoPackage || res.sources[0].GoArtifact != "go-overlay") {
t.Errorf("reserved from %+v, want one source naming the Go package go-overlay", res.sources)
}
}) })
} }
} }
@@ -285,7 +401,7 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) {
return r return r
} }
t.Run("a reservation that cannot be made fails the key and asks nothing", func(t *testing.T) { t.Run("a reservation that cannot be made fails the key and asks nothing", func(t *testing.T) {
r := setup(t, &fakeReservations{filled: true, fail: errors.New("the catalog's versions cannot be read")}) r := setup(t, &fakeReservations{fail: errors.New("the catalog's versions cannot be read")})
v := r.consider(t, "modules/m") v := r.consider(t, "modules/m")
if v.State != builds.BuildFailed || !strings.Contains(v.Error, "no version is reserved") || len(r.asks.Asks()) != 0 { if v.State != builds.BuildFailed || !strings.Contains(v.Error, "no version is reserved") || len(r.asks.Asks()) != 0 {
t.Fatalf("key %+v with %d asks; want failed saying no version is reserved, nothing asked", v, len(r.asks.Asks())) t.Fatalf("key %+v with %d asks; want failed saying no version is reserved, nothing asked", v, len(r.asks.Asks()))
@@ -307,7 +423,7 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) {
if v := r.consider(t, "modules/m"); v.State != builds.BuildDone { if v := r.consider(t, "modules/m"); v.State != builds.BuildDone {
t.Fatalf("first build = %+v, want done", v) t.Fatalf("first build = %+v, want done", v)
} }
res := &fakeReservations{filled: true, released: map[string]bool{fp1: c.released}} res := &fakeReservations{released: map[string]bool{fp1: c.released}}
if c.standing { if c.standing {
res.sources, res.next = []versions.Source{{Fingerprint: fp1}}, "0.1.17" // ReservedFor answers a held reservation res.sources, res.next = []versions.Source{{Fingerprint: fp1}}, "0.1.17" // ReservedFor answers a held reservation
} }
@@ -341,7 +457,6 @@ type realReserve struct {
reservations map[string][]byte reservations map[string][]byte
} }
func (r *realReserve) Filled() bool { return true }
func (r *realReserve) ReleasedFor(context.Context, string, string) (bool, error) { func (r *realReserve) ReleasedFor(context.Context, string, string) (bool, error) {
return false, nil return false, nil
} }
@@ -355,12 +470,8 @@ func (r *realReserve) ReservedFor(ctx context.Context, module, fp string) (versi
return versions.ReservedVersion{}, false, err return versions.ReservedVersion{}, false, err
} }
func (r *realReserve) Built(ctx context.Context, module, version string, digests map[string]string, _ map[string][]meshbuilds.Dependency) error { func (r *realReserve) Built(ctx context.Context, module, version string, digests map[string]string, _ map[string][]meshbuilds.Dependency) error {
for ref, d := range digests { _, _, err := r.Reserver.Built(ctx, module, version, digests, nil)
if _, err := r.Reserver.Built(ctx, module, version, ref, d, nil); err != nil { return err
return err
}
}
return nil
} }
type reserveMap struct{ *memStore } type reserveMap struct{ *memStore }
@@ -386,7 +497,7 @@ func TestABuildAgainKeepsItsOwnStandingNumber(t *testing.T) {
t.Fatalf("first build = %+v, want done", v) t.Fatalf("first build = %+v, want done", v)
} }
store := reserveMap{newMem()} store := reserveMap{newMem()}
real := &realReserve{Reserver: &versions.Reserver{Store: store, Filled: func() bool { return true }, real := &realReserve{Reserver: &versions.Reserver{Store: store,
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }}} ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }}}
raw, _ := json.Marshal(versions.ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: "0.1.30", Fingerprint: fp1, Artifacts: map[string]string{"m:tool": "d"}}) raw, _ := json.Marshal(versions.ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: "0.1.30", Fingerprint: fp1, Artifacts: map[string]string{"m:tool": "d"}})
if _, err := store.Create(context.Background(), versions.ReservedKey("m", "0.1"), raw); err != nil { if _, err := store.Create(context.Background(), versions.ReservedKey("m", "0.1"), raw); err != nil {
@@ -19,7 +19,7 @@ func TestADoneTrunkBuildThatReservedNoneIsGivenAVersionByHand(t *testing.T) {
ctx := context.Background() ctx := context.Background()
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true} res := &fakeReservations{}
r.b.Reserved = res r.b.Reserved = res
if _, err := r.b.ReserveDone(ctx, "m", fp1); err == nil { if _, err := r.b.ReserveDone(ctx, "m", fp1); err == nil {
t.Fatal("a version was reserved for a key that is not built") t.Fatal("a version was reserved for a key that is not built")
@@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"maps" "maps"
"slices" "slices"
"strconv"
"strings" "strings"
"time" "time"
@@ -80,7 +79,8 @@ func (b *Builder) holdsRevision(branch string, source int64, entries []meshbuild
} }
// keptRevisionHolds answers no outcome when the catalog keeps the ask's revision (its catalog revision by number) and that // keptRevisionHolds answers no outcome when the catalog keeps the ask's revision (its catalog revision by number) and that
// revision names every entry of the ask (H-A-205, H-A-222); else failed or could not run, with its words. // revision names every entry of the ask (H-A-205, H-A-222); superseded when it names a newer fingerprint of an entry (H-A-508
// second addendum); else failed or could not run, with its words.
func (b *Builder) keptRevisionHolds(ctx context.Context, run meshbuilds.StepRun, held int64) (outcome, said string) { func (b *Builder) keptRevisionHolds(ctx context.Context, run meshbuilds.StepRun, held int64) (outcome, said string) {
below := fmt.Sprintf("revision %d of %s is not named by the builder's picture, which holds source revision %d", run.Source, run.Branch, held) below := fmt.Sprintf("revision %d of %s is not named by the builder's picture, which holds source revision %d", run.Source, run.Branch, held)
if run.Source < held { if run.Source < held {
@@ -100,14 +100,30 @@ func (b *Builder) keptRevisionHolds(ctx context.Context, run meshbuilds.StepRun,
b.logf("%s: %s, and the catalog's revision %d is of source revision %d, the ask names %d: the step fails, nothing is built", run.Pipeline, below, run.Revision, source, run.Source) b.logf("%s: %s, and the catalog's revision %d is of source revision %d, the ask names %d: the step fails, nothing is built", run.Pipeline, below, run.Revision, source, run.Source)
return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s, and the catalog's revision %d is of source revision %d, the ask names %d", below, run.Revision, source, run.Source) return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s, and the catalog's revision %d is of source revision %d, the ask names %d", below, run.Revision, source, run.Source)
} }
// A step whose fingerprint the catalog's revision no longer names but names a newer one of its module, found below the
// picture or by the revision's number, ends superseded with the superseding fingerprint in its why, never failed (design
// 47 H2 H-A-508 second addendum: one outcome for one fact, found by either check). Failed stays for any other mismatch.
var superseded []string
for _, e := range run.Entries { for _, e := range run.Entries {
if fps[e.Module] != e.Fingerprint { if fps[e.Module] == e.Fingerprint {
b.logf("%s: %s, and the catalog's revision %d names %s at %q, not %s: the step fails, nothing is built", run.Pipeline, below, run.Revision, e.Module, fps[e.Module], e.Fingerprint) continue
return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s, and the catalog's revision %d names %s at %q, not %s", below, run.Revision, e.Module, fps[e.Module], e.Fingerprint)
} }
if fps[e.Module] != "" {
superseded = append(superseded, stepSuperseded(e.Module, e.Fingerprint, fps[e.Module]))
continue
}
b.logf("%s: %s, and the catalog's revision %d names %s at %q, not %s: the step fails, nothing is built", run.Pipeline, below, run.Revision, e.Module, fps[e.Module], e.Fingerprint)
return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s, and the catalog's revision %d names %s at %q, not %s", below, run.Revision, e.Module, fps[e.Module], e.Fingerprint)
}
if len(superseded) > 0 {
said := strings.Join(superseded, "; ")
b.logf("%s: %s, and the catalog's revision %d names newer fingerprints: %s; nothing is built", run.Pipeline, below, run.Revision, said)
return meshbuilds.StepEndedOutcomeSuperseded, said
} }
// Each asked fingerprint is recorded as the branch's, so its build reserves its version (H-A-155) as one the picture // Each asked fingerprint is recorded as the branch's, so its build reserves its version (H-A-155) as one the picture
// took in does; what the picture heard stays as it is, so the newer fingerprint's build is not superseded. // took in does; what the picture heard stays as it is, so the newer fingerprint's build is not superseded. Once the picture
// heard a newer entry of the module on the first branch, H-A-489 overrides H-A-205: the older fingerprint is refused
// superseded (buildEntry), never built or reserved.
b.mu.Lock() b.mu.Lock()
for _, e := range run.Entries { for _, e := range run.Entries {
key, err := builds.BuilderBuildKey(e.Module, e.Fingerprint) key, err := builds.BuilderBuildKey(e.Module, e.Fingerprint)
@@ -134,9 +150,10 @@ func (b *Builder) awaitRevision(ctx context.Context, run meshbuilds.StepRun) (ou
if (run.Revision > 0 && b.KeptRevision != nil) || below { if (run.Revision > 0 && b.KeptRevision != nil) || below {
// By its number (H-A-222), whatever the source the picture holds; for an ask naming none, only below the // By its number (H-A-222), whatever the source the picture holds; for an ask naming none, only below the
// picture (H-A-205). A kept revision of another source or naming other fingerprints is a mismatch the wait // picture (H-A-205). A kept revision of another source or naming other fingerprints is a mismatch the wait
// cannot mend: it fails at once; only a revision the catalog does not answer is waited for. // cannot mend: it fails at once, or ends superseded at once when it names a newer fingerprint of the module (H-A-508
// second addendum); only a revision the catalog does not answer is waited for.
outcome, said := b.keptRevisionHolds(ctx, run, held) outcome, said := b.keptRevisionHolds(ctx, run, held)
if outcome == "" || below || outcome == meshbuilds.StepEndedOutcomeFailed { if outcome == "" || below || outcome == meshbuilds.StepEndedOutcomeFailed || outcome == meshbuilds.StepEndedOutcomeSuperseded {
return outcome, said return outcome, said
} }
} }
@@ -172,14 +189,13 @@ func (b *Builder) awaitRevision(ctx context.Context, run meshbuilds.StepRun) (ou
} }
} }
// **A package with no pin waits for its publish** (design 47 H H-A-192, H-A-165, H-A-183, H-A-184, H-A-185): an entry // **A package with no pin is built against its publisher's version at the key's origin** (design 47 H2 H-A-521, H-A-547 (3),
// keeps a mesh package the registry has not published within the series its module accepts with an empty version. Its // H-A-551; H-A-165): an entry names a mesh package with no version when a mover of the same take-in publishes it (DMC-1). Its
// build, a step ask's or a lane's, first reads the versions the registry seat holds of the path (its verb versions, // build, a step ask's or a lane's, fills that version from the reservation of the module that publishes it (Members) at the
// H-A-194), then waits for the registry seat's published of that package path in that series (the // source revision of the build key's own origin, once that reservation's artifact is published, and else from that module's
// series the module's manifest names in `packages`, else the default; catalogue.Manifest.AcceptedSeries), up to // release recorded at that source revision; never from the newest a registry seat said published. It waits for one, woken by
// PackageWait (the setting package-wait-minutes), and pins the version that event carries; the builder never derives a // each registry seat's published heard (PackagePublished), up to PackageWait (the setting package-wait-minutes). Past the bound
// pin (no release number of the module that holds the package). Past the bound the build fails, naming the package, and // the build fails, naming the package, and nothing is built.
// nothing is built.
// DefaultPackageWait is the bound of a build's wait for a package's publish, its setting package-wait-minutes' default. // DefaultPackageWait is the bound of a build's wait for a package's publish, its setting package-wait-minutes' default.
const DefaultPackageWait = 10 * time.Minute const DefaultPackageWait = 10 * time.Minute
@@ -191,44 +207,46 @@ func (b *Builder) packageWait() time.Duration {
return DefaultPackageWait return DefaultPackageWait
} }
// PackagePublished takes the Go package registry seat's published of one package path in (its name and the version the // PackagePublished is told each registry seat's published of a package (its name and the version the event carries): a build
// event carries, H-A-192): the newest published in the version's series is kept, and a build waiting for the package // waiting for a package's version looks again at the reservations, which the published marked before it is told.
// wakes. A version that is no MAJOR.MINOR.PATCH (a group's tagged version) pins nothing. func (b *Builder) PackagePublished(name, version string) {
func (b *Builder) PackagePublished(path, version string) { if name == "" {
v := strings.TrimPrefix(version, "v")
series, ok := seriesOfVersion(v)
if path == "" || !ok {
return return
} }
b.init() b.init()
b.mu.Lock()
in := b.publishedPins[path]
if in == nil {
in = map[string]string{}
b.publishedPins[path] = in
}
if old := in[series]; old == "" || compareVersions(v, old) > 0 {
in[series] = v
}
b.mu.Unlock()
b.pictureMoved() b.pictureMoved()
} }
// publishedPin is the pin the registry seat's published gave the package path in the series, as Go names it; "" for none. // versionAtOrigin is the version, as Go names it, the module that publishes the package holds at the source revision of the
func (b *Builder) publishedPin(path, series string) string { // key's origin (H-A-547 (3), H-A-551), and words saying why there is none.
b.mu.Lock() func (b *Builder) versionAtOrigin(ctx context.Context, key, pkg string) (version, none string) {
v := b.publishedPins[path][series] if b.Members == nil || b.Reserved == nil {
b.mu.Unlock() return "", "no module that publishes it can be read"
if v == "" {
return ""
} }
return "v" + v module, artifact, found, err := b.Members(ctx, pkg)
if err != nil || !found {
if err != nil {
return "", fmt.Sprintf("the module that publishes it cannot be read: %v", err)
}
return "", "no entry names the module that publishes it"
}
b.mu.Lock()
o := b.origin[key]
b.mu.Unlock()
v, found, err := b.Reserved.VersionAt(ctx, module, artifact, o.Branch, o.Source)
if err != nil {
return "", fmt.Sprintf("the version %s holds at source revision %d cannot be read: %v", module, o.Source, err)
}
if !found {
return "", fmt.Sprintf("%s publishes no version of it at source revision %d of %s", module, o.Source, o.Branch)
}
return "v" + strings.TrimPrefix(v, "v"), ""
} }
// awaitPublished fills each package of packages with no pin from the published of its path within the series the manifest // awaitPublished fills each package of packages with no pin from the version its publisher holds at the key's origin
// with this digest accepts, waiting for one (H-A-192, H-A-165). It answers the packages with every pin, or an outcome and // (versionAtOrigin), waiting for one (H-A-521, H-A-165). It answers the packages with every pin, or an outcome and its words:
// its words: failed past the bound naming the package, could not run when the manifest cannot be read or the builder stops. // failed past the bound naming the package, could not run when the builder stops.
func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string, packages map[string]string) (map[string]string, string, string) { func (b *Builder) awaitPublished(ctx context.Context, module, fp string, packages map[string]string) (map[string]string, string, string) {
var unpinned []string var unpinned []string
for p, v := range packages { for p, v := range packages {
if v == "" { if v == "" {
@@ -239,26 +257,9 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
return packages, "", "" return packages, "", ""
} }
slices.Sort(unpinned) slices.Sort(unpinned)
if b.Manifests == nil { key, err := builds.BuilderBuildKey(module, fp)
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the series %s accepts of %s cannot be read: no manifests", module, unpinned[0])
}
man, err := b.Manifests.Manifest(ctx, digest)
if err != nil { if err != nil {
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the series %s accepts of %s cannot be read: its manifest %s: %v", module, unpinned[0], digest, err) return nil, meshbuilds.StepEndedOutcomeCouldNotRun, err.Error()
}
// What the registry seat holds is read once before the wait (H-A-194): the publishes heard are a cache of it.
for _, p := range unpinned {
if b.PublishedVersions == nil || b.publishedPin(p, man.AcceptedSeries(p)) != "" {
continue
}
vs, err := b.PublishedVersions(ctx, p)
if err != nil {
b.logf("%s at %s: the versions the registry seat holds of %s cannot be read, so the build waits for its publish: %v", module, fp, p, err)
continue
}
for _, v := range vs {
b.PackagePublished(p, v)
}
} }
bound := b.packageWait() bound := b.packageWait()
wait, stop := context.WithTimeout(ctx, bound) // a context's bound, no timer (ADR 0437 §8) wait, stop := context.WithTimeout(ctx, bound) // a context's bound, no timer (ADR 0437 §8)
@@ -269,12 +270,12 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
moved := b.moved moved := b.moved
b.mu.Unlock() b.mu.Unlock()
pins := map[string]string{} pins := map[string]string{}
missing, missingSeries := "", "" missing, why := "", ""
for _, p := range unpinned { for _, p := range unpinned {
series := man.AcceptedSeries(p) v, none := b.versionAtOrigin(wait, key, p)
pins[p] = b.publishedPin(p, series) pins[p] = v
if pins[p] == "" && missing == "" { if v == "" && missing == "" {
missing, missingSeries = p, series missing, why = p, none
} }
} }
if missing == "" { if missing == "" {
@@ -285,58 +286,19 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
} }
return out, "", "" return out, "", ""
} }
notReleased := fmt.Sprintf("package %s has no released version in the series %s", missing, missingSeries) notPublished := fmt.Sprintf("package %s has no published version: %s", missing, why)
if !told { if !told {
b.logf("%s at %s: %s yet: the build waits for its publish, at most %s", module, fp, notReleased, bound) b.logf("%s at %s: %s yet: the build waits for its publish, at most %s", module, fp, notPublished, bound)
told = true told = true
} }
select { select {
case <-moved: case <-moved:
case <-wait.Done(): case <-wait.Done():
if ctx.Err() != nil { if ctx.Err() != nil {
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, notReleased + ": the builder stopped before it was" return nil, meshbuilds.StepEndedOutcomeCouldNotRun, notPublished + ": the builder stopped before it was"
} }
b.logf("%s at %s: %s within %s: the build fails, nothing is built", module, fp, notReleased, bound) b.logf("%s at %s: %s within %s: the build fails, nothing is built", module, fp, notPublished, bound)
return nil, meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notReleased, bound) return nil, meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notPublished, bound)
} }
} }
} }
// seriesOfVersion is a MAJOR.MINOR.PATCH version's series, MAJOR.MINOR; false for any other form.
func seriesOfVersion(v string) (string, bool) {
if _, ok := versionParts(v); !ok {
return "", false
}
major, rest, _ := strings.Cut(v, ".")
minor, _, _ := strings.Cut(rest, ".")
return major + "." + minor, true
}
// versionParts are a MAJOR.MINOR.PATCH version's numbers; false for any other form.
func versionParts(v string) ([3]int, bool) {
var out [3]int
parts := strings.Split(v, ".")
if len(parts) != 3 {
return out, false
}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return out, false
}
out[i] = n
}
return out, true
}
// compareVersions orders two MAJOR.MINOR.PATCH versions numerically.
func compareVersions(a, b string) int {
x, _ := versionParts(a)
y, _ := versionParts(b)
for i := range x {
if x[i] != y[i] {
return x[i] - y[i]
}
}
return 0
}
@@ -104,9 +104,6 @@ type Builder struct {
// time.Now. Node is the node the builder runs on, which asked the build. // time.Now. Node is the node the builder runs on, which asked the build.
Now func() time.Time Now func() time.Time
Node string Node string
// Numbers numbers each trunk build at its claim and records what it was built with (design 51 *The versions*); nil
// numbers nothing, as the builder's program leaves it (design 47 H H-A-159: the reservation numbers, G §369).
Numbers Numbers
// Reserved reserves the version of a trunk build at its start (design 47 G §369); nil reserves nothing. // Reserved reserves the version of a trunk build at its start (design 47 G §369); nil reserves nothing.
Reserved Reservations Reserved Reservations
// Picture answers the source revision the builder's picture of a watched branch holds, false while it holds none (design 47 // Picture answers the source revision the builder's picture of a watched branch holds, false while it holds none (design 47
@@ -124,26 +121,25 @@ type Builder struct {
// when 0. // when 0.
RevisionWait time.Duration RevisionWait time.Duration
// PackageWait bounds a build's wait for the publish of a package its entry names with no pin, its setting // PackageWait bounds a build's wait for the publish of a package its entry names with no pin, its setting
// package-wait-minutes (H-A-165); DefaultPackageWait when 0. Only a registry seat's published heard (PackagePublished) // package-wait-minutes (H-A-165); DefaultPackageWait when 0. The version is its publisher's at the key's origin
// gives a pin (H-A-192). // (H-A-547 (3), H-A-551).
PackageWait time.Duration PackageWait time.Duration
// PublishedVersions asks the Go package registry seat's verb versions for one package path, its versions newest first // RecordBound bounds the record of a reservation's digests after a build ends, its setting record-bound-seconds (design 47
// (H-A-194): read once before a build waits for that package. Nil reads none. // H2 H-A-492): the builder's own bound, never the build's context; DefaultRecordBound when 0.
PublishedVersions func(ctx context.Context, path string) ([]string, error) RecordBound time.Duration
// Forms answers what each node's engine states it reads (ADR 0618 §2, ADR 0624 §1): present, the nodes whose engine // Forms answers what each node's engine states it reads (ADR 0618 §2, ADR 0624 §1): present, the nodes whose engine
// answered when last asked, and counted, every node the assignments names, present or away, a node with no statement // answered when last asked, and counted, every node the assignments names, present or away, a node with no statement
// stating nothing (the baseline's first forms). A done key names each artifact in the forms these keep, the oldest in // stating nothing (the baseline's first forms). A done key names each artifact in the forms these keep, the oldest in
// its single reference, and its needs. Nil: no node states anything, and the first forms are kept. // its single reference, and its needs. Nil: no node states anything, and the first forms are kept.
Forms func() (present, counted map[string][]string) Forms func() (present, counted map[string][]string)
once sync.Once once sync.Once
sem chan struct{} sem chan struct{}
wg sync.WaitGroup wg sync.WaitGroup
mu sync.Mutex mu sync.Mutex
// fillWaits are the builds that said wait-held for the fill (module.fingerprint), so it is said once.
fillWaits sync.Map
known map[string]meshcatalog.ModulesByModuleValue // by modules key: the first watched branch's known map[string]meshcatalog.ModulesByModuleValue // by modules key: the first watched branch's
heard map[string]meshcatalog.ModulesByModuleValue // by branch and module (take): what supersedes what heard map[string]meshcatalog.ModulesByModuleValue // by branch and module (take): what supersedes what
heardAt map[string]Origin // by branch and module (take): the revision the heard entry came from (H-A-557)
origin map[string]Origin // by build key: the catalog revision its entry came from (take) origin map[string]Origin // by build key: the catalog revision its entry came from (take)
edges map[string][]meshcatalog.Edge // by build key: the edges of its entry (take), whose parts a package-published names edges map[string][]meshcatalog.Edge // by build key: the edges of its entry (take), whose parts a package-published names
deps map[string]map[string][]meshbuilds.Dependency // by build key: what each artifact resolved and was built with (keepDependencies) deps map[string]map[string][]meshbuilds.Dependency // by build key: what each artifact resolved and was built with (keepDependencies)
@@ -174,9 +170,10 @@ type Builder struct {
builds map[string]context.CancelCauseFunc builds map[string]context.CancelCauseFunc
// moved is closed and made again at each entry the picture takes in or drops: the step asks waiting for a revision wake. // moved is closed and made again at each entry the picture takes in or drops: the step asks waiting for a revision wake.
moved chan struct{} moved chan struct{}
// publishedPins are the newest version a registry seat said published, by package path and series (PackagePublished): // supersededSaid are the build keys refused as superseded (H-A-489), so each is said once.
// a package with no pin waits for one (H-A-192). supersededSaid sync.Map
publishedPins map[string]map[string]string // passedOverSaid are the build keys and heard fingerprints passed over as not newer (H-A-557), so each is said once.
passedOverSaid sync.Map
} }
type planned struct { type planned struct {
@@ -201,13 +198,13 @@ func (b *Builder) init() {
b.sem = make(chan struct{}, limit) b.sem = make(chan struct{}, limit)
b.trunkFP = map[string]bool{} b.trunkFP = map[string]bool{}
b.heard, b.known = map[string]meshcatalog.ModulesByModuleValue{}, map[string]meshcatalog.ModulesByModuleValue{} b.heard, b.known = map[string]meshcatalog.ModulesByModuleValue{}, map[string]meshcatalog.ModulesByModuleValue{}
b.heardAt = map[string]Origin{}
b.origin, b.edges = map[string]Origin{}, map[string][]meshcatalog.Edge{} b.origin, b.edges = map[string]Origin{}, map[string][]meshcatalog.Edge{}
b.inflight, b.again, b.plans, b.tried = map[string]bool{}, map[string]meshcatalog.ModulesByModuleValue{}, map[string]planned{}, map[string]bool{} b.inflight, b.again, b.plans, b.tried = map[string]bool{}, map[string]meshcatalog.ModulesByModuleValue{}, map[string]planned{}, map[string]bool{}
b.published, b.held, b.waiting = map[string]bool{}, map[string]bool{}, map[string]map[string]chan string{} b.published, b.held, b.waiting = map[string]bool{}, map[string]bool{}, map[string]map[string]chan string{}
b.hands, b.events = map[string]*handWatch{}, map[string]bool{} b.hands, b.events = map[string]*handWatch{}, map[string]bool{}
b.builds = map[string]context.CancelCauseFunc{} b.builds = map[string]context.CancelCauseFunc{}
b.moved = make(chan struct{}) b.moved = make(chan struct{})
b.publishedPins = map[string]map[string]string{}
}) })
} }
@@ -261,6 +258,7 @@ func (b *Builder) EntryGone(branch string, first bool, module string) {
b.init() b.init()
b.mu.Lock() b.mu.Lock()
delete(b.heard, branch+"\x00"+module) delete(b.heard, branch+"\x00"+module)
delete(b.heardAt, branch+"\x00"+module)
b.mu.Unlock() b.mu.Unlock()
b.pictureMoved() b.pictureMoved()
if first { if first {
@@ -289,12 +287,19 @@ func (b *Builder) take(ctx context.Context, o Origin, key string, m meshcatalog.
b.mu.Lock() b.mu.Lock()
hk := o.Branch + "\x00" + key hk := o.Branch + "\x00" + key
old, had := b.heard[hk] old, had := b.heard[hk]
b.heard[hk] = m oldAt := b.heardAt[hk]
if o.First { // An entry of an older module graph revision than the one heard before it neither replaces it as the branch's newest nor
b.known[key] = m // withdraws its build (H-A-557): it is still built for the older revision's pipeline.
before, known := newerRevision(oldAt, o)
older := had && known && before
if !older {
b.heard[hk], b.heardAt[hk] = m, o
if o.First {
b.known[key] = m
}
} }
var superseded context.CancelCauseFunc var superseded context.CancelCauseFunc
if had && old.Fp2 != "" && old.Fp2 != m.Fp2 { if had && !older && old.Fp2 != "" && old.Fp2 != m.Fp2 {
if ok, err := builds.BuilderBuildKey(key, old.Fp2); err == nil { if ok, err := builds.BuilderBuildKey(key, old.Fp2); err == nil {
superseded = b.builds[ok] superseded = b.builds[ok]
} }
@@ -306,15 +311,81 @@ func (b *Builder) take(ctx context.Context, o Origin, key string, m meshcatalog.
b.edges[bk] = e b.edges[bk] = e
} }
b.mu.Unlock() b.mu.Unlock()
if older {
b.logf("%s at %s (revision %d, source %d): older than the entry heard at %s (revision %d, source %d): it stays the newest (H-A-557)",
key, m.Fp2, o.Revision, o.Source, old.Fp2, oldAt.Revision, oldAt.Source)
}
b.pictureMoved() b.pictureMoved()
if superseded != nil { if superseded != nil {
// A newer fingerprint of the module: the build of the older one in flight is taken out, and its asks are withdrawn // A newer fingerprint of the module: the build of the older one in flight is taken out, and its asks are withdrawn
// from the build seats (ADR 0664 §4). // from the build seats (ADR 0664 §4).
superseded(buildrun.Withdrawn{Why: "the build of " + key + " at " + old.Fp2 + " was superseded by the fingerprint " + m.Fp2}) superseded(buildrun.Withdrawn{Why: supersededWhy(key, old.Fp2, m.Fp2)})
} }
b.consider(ctx, key, m) b.consider(ctx, key, m)
} }
// supersededWhy is the words of a build withdrawn because a newer fingerprint of its module superseded it.
func supersededWhy(module, fp, newer string) string {
return "the build of " + module + " at " + fp + " was superseded by the fingerprint " + newer
}
// withdrawnPrefix opens the error of a key whose build was withdrawn (H-A-225, ADR 0664 §4). It is final for its fingerprint
// (H-A-489): no look builds it again; a person's build again does.
const withdrawnPrefix = "withdrawn: "
// supersededBy is the fingerprint that supersedes fp, a fingerprint of module whose build key is key, when fp is of its
// registration's first watched branch and is no longer the newest entry heard on that branch (H-A-489); "" otherwise. A key no
// entry named is of the first branch, as originOf has it.
func (b *Builder) supersededBy(module, key, fp string) string {
b.mu.Lock()
defer b.mu.Unlock()
o, ok := b.origin[key]
if !ok {
o = Origin{First: true}
}
if !o.First {
return ""
}
newest, heard := b.heard[o.Branch+"\x00"+module]
if !heard || newest.Fp2 == "" || newest.Fp2 == fp {
return ""
}
// The newest entry heard supersedes fp only when it is of a module graph revision newer than fp's own (H-A-557): the
// picture may lag the revision a step ask named (its kept revision read from the catalog), and an entry it heard of an
// older or the same revision is passed over, said once per key.
at := b.heardAt[o.Branch+"\x00"+module]
if newer, known := newerRevision(at, o); known && !newer {
if _, said := b.passedOverSaid.LoadOrStore(key+"\x00"+newest.Fp2, true); !said {
b.logf("%s at %s (revision %d, source %d): the entry heard at %s (revision %d, source %d) is not of a newer revision: not superseded by it (H-A-557)",
module, fp, o.Revision, o.Source, newest.Fp2, at.Revision, at.Source)
}
return ""
}
return newest.Fp2
}
// newerRevision says whether a is of a newer module graph revision than b (H-A-557): by their catalog revision numbers when
// both name one, else by their source revisions when both name one; known is false when neither pair is named, as for an
// entry taken in with no branch.
func newerRevision(a, b Origin) (newer, known bool) {
switch {
case a.Revision > 0 && b.Revision > 0:
return a.Revision > b.Revision, true
case a.Source > 0 && b.Source > 0:
return a.Source > b.Source, true
}
return false, false
}
// saySuperseded says, once per key, that the build of fp is refused as superseded by newer (H-A-489), and gives the words.
func (b *Builder) saySuperseded(module, key, fp, newer string) string {
why := "is not built: superseded by " + newer + ", the newest entry heard on its first branch"
if _, said := b.supersededSaid.LoadOrStore(key, true); !said {
b.logf("%s at %s: %s", module, fp, why)
}
return why
}
// ModuleOf is a catalog entry in the form the builder builds by: its fingerprint, manifest digest, source (repository, // ModuleOf is a catalog entry in the form the builder builds by: its fingerprint, manifest digest, source (repository,
// directory, commit; no source stamp, design 47 H H-A-48), the toolchains its fingerprint was computed with, the bases it is // directory, commit; no source stamp, design 47 H H-A-48), the toolchains its fingerprint was computed with, the bases it is
// built against, its packages and needs, and the named paths of its artifacts when every artifact names them. // built against, its packages and needs, and the named paths of its artifacts when every artifact names them.
@@ -637,6 +708,12 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
whyEnded = fmt.Sprintf(format, args...) whyEnded = fmt.Sprintf(format, args...)
b.logf("%s at %s: %s", module, m.Fp2, whyEnded) b.logf("%s at %s: %s", module, m.Fp2, whyEnded)
} }
// A fingerprint no longer the newest entry heard on its first branch is neither reserved for nor built (H-A-489): two
// fingerprints of one module never take the series from each other.
if newer := b.supersededBy(module, key, m.Fp2); newer != "" {
whyEnded = b.saySuperseded(module, key, m.Fp2, newer)
return
}
plan, planErr, read := b.planOf(ctx, m.Manifest) plan, planErr, read := b.planOf(ctx, m.Manifest)
var noModule *NoBuildModule var noModule *NoBuildModule
if errors.As(planErr, &noModule) { if errors.As(planErr, &noModule) {
@@ -670,19 +747,13 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
byEvent := b.events[key] byEvent := b.events[key]
delete(b.events, key) delete(b.events, key)
b.mu.Unlock() b.mu.Unlock()
var numbering versions.Numbering
if trunk && planErr == nil && !nothing {
var goOn bool
if numbering, goOn = b.number(ctx, module, m, plan); !goOn {
end("is not built yet: it waits for its package's floor, nothing is claimed")
return
}
}
// Only a build of the registration's first watched branch reserves and releases a version (design 47 G §371). // Only a build of the registration's first watched branch reserves and releases a version (design 47 G §371).
reserving := trunk && b.originOf(key).First && planErr == nil && !nothing && b.reserves(ctx, module, m, plan) reserving := trunk && b.originOf(key).First && planErr == nil && !nothing && b.reserves(ctx, module, m, plan)
if reserving && b.waitFill(module, m) { if trunk && b.originOf(key).First && planErr == nil && !nothing && !reserving {
end("is not built yet: wait-held, the catalog has not said versions-filled") // A done build whose digests its end did not record is recorded at the next look (design 47 H2 H-A-492).
return if _, err := b.RecordAgain(ctx, module, m.Fp2, "at a look"); err != nil {
b.logf("%v", err)
}
} }
// A key built again by hand is taken over as it stands too: one left building by a look that ended without its write // A key built again by hand is taken over as it stands too: one left building by a look that ended without its write
// (issue 1966) is the hand tool's to finish. // (issue 1966) is the hand tool's to finish.
@@ -727,27 +798,27 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
} }
} }
var reserved versions.ReservedVersion var reserved versions.ReservedVersion
hasReserved := false hasReserved, supersededNow := false, ""
if rebuild && cl.Build.State == builds.BuildBuilding { if rebuild && cl.Build.State == builds.BuildBuilding {
// Reserved as A-490b amended by H-A-225 has it: this fingerprint's standing reservation is kept while it is unreleased // Reserved as A-490b amended by H-A-225 has it: this fingerprint's standing reservation is kept while it is unreleased
// and above the highest the catalog's versions answers, else the next above that highest is taken (A-455); the build's // and above the highest the catalog's versions answers, else the next above that highest is taken (A-455); the build's
// own publish then runs. // own publish then runs.
if b.Reserved.Filled() { reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), true)
reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), true)
}
reserving = true reserving = true
} else if reserving && cl.Build.State != builds.BuildDone { } else if reserving && cl.Build.State != builds.BuildDone {
reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), false) // Looked at again just before it reserves (H-A-489): a newer entry heard since the claim is not taken over.
if supersededNow = b.supersededBy(module, key, m.Fp2); supersededNow == "" {
reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), false)
}
} }
var result builds.BuilderBuild var result builds.BuilderBuild
if reserving && !hasReserved && cl.Build.State != builds.BuildDone { if supersededNow != "" {
// Ended as the newer entry's take-in withdraws a build in flight: final for this fingerprint.
result = builds.BuilderBuild{State: builds.BuildFailed, Error: keyError([]string{withdrawnPrefix + supersededWhy(module, m.Fp2, supersededNow)})}
} else if reserving && !hasReserved && cl.Build.State != builds.BuildDone {
// A trunk build that reserves is never built without its version: it would end done and publish nothing, and its key would // A trunk build that reserves is never built without its version: it would end done and publish nothing, and its key would
// stay done, never built again (A-490). The key fails with why and is taken again at the next look or by builder_build_again. // stay done, never built again (A-490). The key fails with why and is taken again at the next look or by builder_build_again.
result = failed("no version is reserved for this build: the builder's journal says why, and it is built again once one can be") result = failed("no version is reserved for this build: the builder's journal says why, and it is built again once one can be")
} else if numbering.Refused != "" && cl.Build.State != builds.BuildDone {
// Refused, naming the state it could not read, and built against no guess (ADR 0666 §15; design 47, test 70): the key
// fails with why, and is taken again at the next look.
result = failed("%s", numbering.Refused)
} else if nothing { } else if nothing {
// A manifest with no artifact is built by building nothing: its key is done with no artifact, claimed and written as // A manifest with no artifact is built by building nothing: its key is done with no artifact, claimed and written as
// any other, so the controller has a done key to register it from (issue 1613, ADR 0478 clause 1, ADR 0501 clause 1). // any other, so the controller has a done key to register it from (issue 1613, ADR 0478 clause 1, ADR 0501 clause 1).
@@ -765,7 +836,7 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
var w buildrun.Withdrawn var w buildrun.Withdrawn
if ctx.Err() == nil && errors.As(context.Cause(run), &w) { if ctx.Err() == nil && errors.As(context.Cause(run), &w) {
// Taken out, not stopped: the key says so, and the asks are withdrawn (the asker dropped them). // Taken out, not stopped: the key says so, and the asks are withdrawn (the asker dropped them).
result = builds.BuilderBuild{State: builds.BuildFailed, Error: keyError([]string{"withdrawn: " + w.Why})} result = builds.BuilderBuild{State: builds.BuildFailed, Error: keyError([]string{withdrawnPrefix + w.Why})}
} }
} }
if ctx.Err() != nil { if ctx.Err() != nil {
@@ -797,18 +868,18 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
ended := LogEnded(module, m, "", b.Node, b.now(), result) ended := LogEnded(module, m, "", b.Node, b.now(), result)
ended.OutOfStep = b.takeOutOfStep(key) // the generated files the build module's compare found out of step (design 26) ended.OutOfStep = b.takeOutOfStep(key) // the generated files the build module's compare found out of step (design 26)
b.logBuild(ended) b.logBuild(ended)
if result.State == builds.BuildDone && b.Numbers != nil && len(numbering.Versions) > 0 {
if err := b.Numbers.Built(ctx, module, m, plan, numbering, result.Artifacts); err != nil {
b.logf("%s: %v", cl.Key, err)
}
}
if result.State == builds.BuildDone && hasReserved { if result.State == builds.BuildDone && hasReserved {
digests := map[string]string{} digests := map[string]string{}
for _, a := range result.Artifacts { for _, a := range result.Artifacts {
digests[module+":"+a.Name] = a.Digest digests[module+":"+a.Name] = a.Digest
} }
if err := b.Reserved.Built(ctx, module, reserved.Version, digests, b.takeDependencies(key)); err != nil { // Under the builder's own bound, never the build's context: a takeover or an end that cancels it no longer leaves a passed
b.logf("%s: the digests of %s are not recorded: %v", cl.Key, reserved.Version, err) // build unrecorded, so unreleased (design 47 H2 H-A-492).
rec, stop := b.recordContext(ctx)
err := b.Reserved.Built(rec, module, reserved.Version, digests, b.takeDependencies(key))
stop()
if err != nil {
b.logf("%s: the digests of %s are not recorded: %v; recorded again at the builder's next look or start", cl.Key, reserved.Version, err)
} }
} }
if result.State == builds.BuildFailed { if result.State == builds.BuildFailed {
@@ -860,7 +931,6 @@ type lane struct {
toolchain *builds.ToolchainUsed toolchain *builds.ToolchainUsed
digests map[string]string // artifact -> digest digests map[string]string // artifact -> digest
references map[string]string // artifact -> the reference an image was pushed to (a trunk build only) references map[string]string // artifact -> the reference an image was pushed to (a trunk build only)
imports []string // the mesh packages the lane's programs import, as its build module answered them
resolved map[string][]sdkstep.AskResolved // artifact -> the mesh packages its build resolved (design 47 G §466) resolved map[string][]sdkstep.AskResolved // artifact -> the mesh packages its build resolved (design 47 G §466)
tcDigest string // the digest of the toolchain program the building node ran, kind 3's (design 47 G §466, §472) tcDigest string // the digest of the toolchain program the building node ran, kind 3's (design 47 G §466, §472)
tcVersion string // and the version it ran tcVersion string // and the version it ran
@@ -1016,7 +1086,7 @@ func (b *Builder) build(ctx context.Context, module string, m meshcatalog.Module
used = nil used = nil
} }
done := builds.BuilderBuild{State: builds.BuildDone, By: b.Claimer.By, Manifest: m.Manifest, Step: step, Artifacts: artifacts, Toolchains: used, done := builds.BuilderBuild{State: builds.BuildDone, By: b.Claimer.By, Manifest: m.Manifest, Step: step, Artifacts: artifacts, Toolchains: used,
Imports: importsOf(lanes), Needs: forms.Current.Needs(artifacts), Packages: pinsOf(lanes)} // the forms it is written in (ADR 0618 §1) Needs: forms.Current.Needs(artifacts), Packages: pinsOf(lanes)} // the forms it is written in (ADR 0618 §1)
for _, l := range lanes { for _, l := range lanes {
if l.kept != "" { if l.kept != "" {
done.KeptOn = l.node // design 47 G §671: the build node that keeps the build done.KeptOn = l.node // design 47 G §671: the build node that keeps the build
@@ -1167,9 +1237,9 @@ func (b *Builder) runLane(ctx context.Context, l *lane, repository string, m mes
if language == sdkstep.AskGo && job.Fetch != nil && len(m.Packages) > 0 { if language == sdkstep.AskGo && job.Fetch != nil && len(m.Packages) > 0 {
// The versions of the mesh packages the fingerprint was computed with (novox/hq ADR 0573 §2): the build module writes // The versions of the mesh packages the fingerprint was computed with (novox/hq ADR 0573 §2): the build module writes
// them into the workspace, whatever the repository's go.mod names. A package the entry names with no pin waits for // them into the workspace, whatever the repository's go.mod names. A package the entry names with no pin waits for
// its publish and is built with the version that publish carries; past the bound the lane fails naming it, and no // its publish and is built with the version its publisher holds at the key's origin; past the bound the lane fails
// ask is put (H-A-192, H-A-165). // naming it, and no ask is put (H-A-521, H-A-547 (3), H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Manifest, m.Packages) pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Packages)
if outcome != "" { if outcome != "" {
l.err = errors.New(said) l.err = errors.New(said)
return return
@@ -1241,7 +1311,6 @@ func (b *Builder) runLane(ctx context.Context, l *lane, repository string, m mes
l.err = fmt.Errorf("the ask of %s on %s answered what is not a build: %s", l.module, step.Node, step.Result) l.err = fmt.Errorf("the ask of %s on %s answered what is not a build: %s", l.module, step.Node, step.Result)
return return
} }
l.imports = answer.Imports
l.kept = answer.Kept l.kept = answer.Kept
if answer.Toolchain != nil { if answer.Toolchain != nil {
l.tcDigest, l.tcVersion = answer.Toolchain.Digest, answer.Toolchain.Version l.tcDigest, l.tcVersion = answer.Toolchain.Digest, answer.Toolchain.Version
@@ -1322,8 +1391,7 @@ func LogEnded(module string, m meshcatalog.ModulesByModuleValue, ref, by string,
} }
e.Made = append([]builds.BuiltArtifact(nil), result.Artifacts...) e.Made = append([]builds.BuiltArtifact(nil), result.Artifacts...)
e.KeptOn = result.KeptOn e.KeptOn = result.KeptOn
e.Imports = append([]string(nil), result.Imports...) // the indexer keeps them on the module (novox/hq ADR 0593 §2) e.Error, e.Step = result.Error, result.Step // a failed build's reason, not only its outcome
e.Error, e.Step = result.Error, result.Step // a failed build's reason, not only its outcome
e.Needs = append([]string(nil), result.Needs...) e.Needs = append([]string(nil), result.Needs...)
return e return e
} }
@@ -1358,9 +1426,6 @@ func (b *Builder) takeOutOfStep(key string) []string {
return files return files
} }
// importsOf are the mesh packages the lanes' programs import, as their build modules answered them (novox/hq ADR 0593
// §2): sorted and each once; nil when none answered any. A lane kept from a prior build answered none, so a build that
// kept one reports only what it built.
// pinsOf is the mesh packages' versions the lanes were built with (H-A-207), nil when none was pinned. // pinsOf is the mesh packages' versions the lanes were built with (H-A-207), nil when none was pinned.
func pinsOf(lanes []*lane) map[string]string { func pinsOf(lanes []*lane) map[string]string {
var out map[string]string var out map[string]string
@@ -1375,19 +1440,6 @@ func pinsOf(lanes []*lane) map[string]string {
return out return out
} }
func importsOf(lanes []*lane) []string {
seen := map[string]bool{}
for _, l := range lanes {
for _, p := range l.imports {
seen[p] = true
}
}
if len(seen) == 0 {
return nil
}
return slices.Sorted(maps.Keys(seen))
}
// SittingOutWords says, per node that is not on the agreed toolchain of a language, that it sits out and which version // SittingOutWords says, per node that is not on the agreed toolchain of a language, that it sits out and which version
// it has against the agreed one: "ace sits out: typescript 26.12.1, agreed 26.13.0" (novox/hq ADR 0584 clause 2). // it has against the agreed one: "ace sits out: typescript 26.12.1, agreed 26.13.0" (novox/hq ADR 0584 clause 2).
func SittingOutWords(language string, a sdkstep.Agreement) []string { func SittingOutWords(language string, a sdkstep.Agreement) []string {
@@ -23,8 +23,6 @@ import (
stdio "git.novox.be/novox/mesh-sdk/go" stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-builder/internal/versions"
) )
// buildModules simulates the two build modules on the nodes: a long tool answers a step and key at once and writes the // buildModules simulates the two build modules on the nodes: a long tool answers a step and key at once and writes the
@@ -229,7 +227,7 @@ var (
) )
func TestABundleAndAnArchiveAreBuiltOnOneNodeAndDone(t *testing.T) { // 1607/AC7, ADR 0478 clauses 1, 4 func TestABundleAndAnArchiveAreBuiltOnOneNodeAndDone(t *testing.T) { // 1607/AC7, ADR 0478 clauses 1, 4
t.Run("the imports a build answers reach the done key and the log", importsABuildAnswersReachTheDoneKeyAndTheLog) t.Run("the imports a build answers reach neither the done key nor the log", importsABuildAnswersReachNeitherTheDoneKeyNorTheLog)
t.Run("a kept build names its node in its end", aKeptBuildNamesItsNodeInItsEnd) t.Run("a kept build names its node in its end", aKeptBuildNamesItsNodeInItsEnd)
t.Run("the out-of-step files a build answers reach the log", outOfStepFilesABuildAnswersReachTheLog) t.Run("the out-of-step files a build answers reach the log", outOfStepFilesABuildAnswersReachTheLog)
t.Run("ADR 0624: a done key keeps each form a counted node reads", aDoneKeyKeepsEachFormACountedNodeReads) t.Run("ADR 0624: a done key keeps each form a counted node reads", aDoneKeyKeepsEachFormACountedNodeReads)
@@ -333,8 +331,9 @@ func TestAWithdrawnBuildEndsWithdrawn(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
asked, release := make(chan struct{}), make(chan struct{}) asked, release := make(chan struct{}), make(chan struct{})
answer := r.answer answer := r.answer
var once sync.Once
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step { r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
close(asked) once.Do(func() { close(asked) })
<-release <-release
return answer(a) return answer(a)
} }
@@ -356,6 +355,85 @@ func TestAWithdrawnBuildEndsWithdrawn(t *testing.T) {
if v := valueOf(t, r.st, r.key); v.State != builds.BuildFailed || !strings.Contains(v.Error, "withdrawn: its reservation 0.1.3 was taken over") { if v := valueOf(t, r.st, r.key); v.State != builds.BuildFailed || !strings.Contains(v.Error, "withdrawn: its reservation 0.1.3 was taken over") {
t.Fatalf("the key = %+v, want failed withdrawn naming the take-over", v) t.Fatalf("the key = %+v, want failed withdrawn naming the take-over", v)
} }
// H-A-489: withdrawn is final for the fingerprint: a later look builds it not again; a person's build again does.
n, rev := len(r.asks.Asks()), r.st.revs[r.key]
r.b.Reconsider(context.Background())
r.b.Wait()
if v := valueOf(t, r.st, r.key); len(r.asks.Asks()) != n || r.st.revs[r.key] != rev || !strings.HasPrefix(v.Error, "withdrawn: ") {
t.Errorf("a later look built the withdrawn key again: %d asks (was %d), the key %+v", len(r.asks.Asks()), n, v)
}
if cl, err := r.b.Claimer.Claim(context.Background(), "m", fp1, mdigest('a'), ClaimOptions{ByHand: true}); err != nil || cl == nil {
t.Errorf("a person's build again of the withdrawn key was not claimed: %v", err)
}
}
// H-A-489 (review round 1): a newer entry of the first branch heard between the older build's claim and its reservation is
// not taken over: the older key ends failed withdrawn with no reservation, and the newer reserves.
func TestANewerEntryHeardBeforeTheReservationIsNotTakenOver(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{}
r.b.Reserved = res
newer, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp2: fp2, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)})
if err != nil {
t.Fatal(err)
}
r.st.before = func() { r.b.Module(context.Background(), "m", newer) } // at the older key's claim
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
if v := valueOf(t, r.st, r.key); v.State != builds.BuildFailed || !strings.HasPrefix(v.Error, "withdrawn: ") || !strings.Contains(v.Error, "superseded by the fingerprint "+fp2) {
t.Errorf("the older key = %+v, want failed withdrawn, superseded by %s", v, fp2)
}
if len(res.sources) != 1 || res.sources[0].Fingerprint != fp2 {
t.Errorf("reserved %+v, want one reservation, the newer's", res.sources)
}
}
// H-A-489: a fingerprint of the first branch that is no longer its newest entry heard is neither reserved for nor built, and
// said once; the again loop that looks at it later builds nothing.
func TestAnOlderFingerprintAskedAfterANewerEntryIsRefused(t *testing.T) {
r := newRig(t, goBundle)
var mu sync.Mutex
var said []string
r.b.Logf = func(f string, a ...any) { mu.Lock(); said = append(said, fmt.Sprintf(f, a...)); mu.Unlock() }
r.bm.fails["ace/build_go_build"] = "go build of tool: boom"
older := meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp2: fp1, Manifest: mdigest('a'),
Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)}
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
delete(r.bm.fails, "ace/build_go_build")
newer := older
newer.Fp2 = fp2
data, err := meshcatalogclient.EncodeModule(newer)
if err != nil {
t.Fatal(err)
}
r.b.Module(context.Background(), "m", data)
r.b.Wait()
rev := r.st.revs[r.key]
for range 2 {
r.b.consider(context.Background(), "m", older) // as consider's again loop or a step's look takes it
r.b.Wait()
}
if v := valueOf(t, r.st, r.key); v.State != builds.BuildFailed || r.st.revs[r.key] != rev {
t.Errorf("the older key = %+v at revision %d (was %d), want it left as it failed", v, r.st.revs[r.key], rev)
}
k2, _ := builds.BuilderBuildKey("m", fp2)
if v := valueOf(t, r.st, k2); v.State != builds.BuildDone {
t.Errorf("the newer key = %+v, want done", v)
}
mu.Lock()
defer mu.Unlock()
n := 0
for _, l := range said {
if strings.Contains(l, fp1+": is not built: superseded by "+fp2) {
n++
}
}
if n != 1 {
t.Errorf("superseded said %d times, want once: %q", n, said)
}
} }
// 1887/AC1, AC2: a trunk fingerprint with no key is one ask on the Go seat's delivery stream, named in the building key // 1887/AC1, AC2: a trunk fingerprint with no key is one ask on the Go seat's delivery stream, named in the building key
@@ -363,14 +441,12 @@ func TestAWithdrawnBuildEndsWithdrawn(t *testing.T) {
func TestATrunkFingerprintIsOneAskOnTheDeliveryStream(t *testing.T) { func TestATrunkFingerprintIsOneAskOnTheDeliveryStream(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.asks.Answer = nil // no node has pulled it yet r.asks.Answer = nil // no node has pulled it yet
// Issue 1585 (ADR 0573 §2): the ask carries the module's pins; a package the entry keeps with no version (none // Issue 1585 (ADR 0573 §2): the ask carries the module's pins (a package with none is filled at the key's origin, the
// published, design 47 H-A-161) is pinned at the version the registry seat's published carries (H-A-192), never // step tests' H-A-547 (3)).
// asked without it.
r.b.PackagePublished("git.novox.be/novox/mesh-contracts/go/seats/x", "v0.1.7")
sdk := buildstep.PackageVersions{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": "v0.1.7"} sdk := buildstep.PackageVersions{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": "v0.1.7"}
data, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", data, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp2: fp1, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains), Fp2: fp1, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains),
Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": ""}}) Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": "v0.1.7"}})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -472,88 +548,21 @@ func TestABundleAndAnImageOfOneModuleBuildOnOneNodeEach(t *testing.T) { // 1705a
} }
} }
func TestATrunkImageCallCarriesPublish(t *testing.T) { // 1705b; design 51 *The versions*: numbered at the claim func TestATrunkImageCallCarriesPublish(t *testing.T) { // 1705b; design 47 H §756: a trunk build is claimed and built, asking no floor
r := newRig(t, imageArt) r := newRig(t, imageArt)
r.puller = "ace" r.puller = "ace"
nums := &fakeNumbers{wait: "m/img: the package waits for its floor"}
r.b.Numbers = nums
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
if _, ok := r.st.vals[r.key]; ok || nums.numbered != 1 {
t.Fatalf("a build waiting for its floor was claimed (numbered %d times)", nums.numbered)
}
nums.wait, nums.versions = "", map[string]string{"img": "0.1.4"}
r.consider(t, "modules/m") r.consider(t, "modules/m")
calls := r.bm.callsOf("build_image_build") calls := r.bm.callsOf("build_image_build")
if len(calls) != 1 || calls[0].body.(map[string]any)["publish"] != true { if len(calls) != 1 || calls[0].body.(map[string]any)["publish"] != true {
t.Errorf("calls = %+v, want publish true", calls) t.Errorf("calls = %+v, want publish true", calls)
} }
if nums.built["img"] != digest {
t.Errorf("the built digest recorded = %v, want %s for img", nums.built, digest)
}
if nums.done != nil {
t.Errorf("a build still to make was numbered with done digests %v", nums.done)
}
// The indexer's packages state names a package of the module (PackageNamed): the done build is looked at again and // The indexer's packages state names a package of the module (PackageNamed): the done build is looked at again and
// numbered with its key's digests, so version.numbered carries them for the late publish; nothing is built again. // nothing is built again.
looks := nums.numbered
r.b.PackageNamed(context.Background(), "m") r.b.PackageNamed(context.Background(), "m")
r.b.Wait() r.b.Wait()
if nums.numbered != looks+1 || nums.done["img"] != digest || len(r.bm.callsOf("build_image_build")) != 1 { if n := len(r.bm.callsOf("build_image_build")); n != 1 {
t.Errorf("a named package's done build: numbered %d more times with %v, %d image builds; want once with img %s and no build", t.Errorf("a named package's done build was built again: %d image builds, want 1", n)
nums.numbered-looks, nums.done, len(r.bm.callsOf("build_image_build")), digest)
} }
// A late look that numbers a done build with no reservation is said aloud, naming builder_reserve_done (G §349, A-455).
late := &logged{}
r.b.Logf, r.b.Reserved = late.logf, &fakeReservations{filled: true}
r.b.PackageNamed(context.Background(), "m")
r.b.Wait()
if !late.has("late look numbered", "builder_reserve_done") {
t.Errorf("a late look numbered a done build with no reservation and said %v", late.lines)
}
r.b.Reserved = nil
looks = nums.numbered
r.b.PackageNamed(context.Background(), "other")
r.b.Wait()
if nums.numbered != looks {
t.Errorf("a module the builder does not know was looked at")
}
// D-B5 (ADR 0666 §15; design 47, test 70): a build whose published packages cannot be read is refused, naming the
// state: its key fails with why, and nothing is built.
unread := newRig(t, imageArt)
unread.puller = "ace"
unread.b.Numbers = &fakeNumbers{refused: "m/img: refused: the builder's state versions (bucket mesh-delivery-builder_versions) cannot be read"}
unread.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
unread.b.Wait()
if v := valueOf(t, unread.st, unread.key); v.State != builds.BuildFailed || !strings.Contains(v.Error, "state versions") || len(unread.bm.callsOf("build_image_build")) != 0 {
t.Errorf("a build with its versions unread: key %+v, %d builds; want failed naming the state, none built", v, len(unread.bm.callsOf("build_image_build")))
}
}
// fakeNumbers is Numbers that answers what it is set to and keeps the digests a done build recorded.
type fakeNumbers struct {
wait string
versions map[string]string
numbered int
built map[string]string
done map[string]string // the done key's digests the last look numbered with
refused string // answered as Numbering.Refused
}
func (f *fakeNumbers) Number(_ context.Context, _ string, _ meshcatalog.ModulesByModuleValue, _ Plan, done map[string]string) (versions.Numbering, error) {
f.done = done
f.numbered++
return versions.Numbering{Wait: f.wait, Versions: f.versions, Refused: f.refused}, nil
}
func (f *fakeNumbers) Built(_ context.Context, _ string, _ meshcatalog.ModulesByModuleValue, _ Plan, got versions.Numbering, made []builds.BuiltArtifact) error {
f.built = map[string]string{}
for _, a := range made {
if got.Versions[a.Name] != "" {
f.built[a.Name] = a.Digest
}
}
return nil
} }
func TestAnUnpinnedUpstreamFailsNotPinnedAndIsNeverBuiltAgain(t *testing.T) { // B3, ADR 0498 clause 4 func TestAnUnpinnedUpstreamFailsNotPinnedAndIsNeverBuiltAgain(t *testing.T) { // B3, ADR 0498 clause 4
@@ -18,12 +18,13 @@ import (
// number is needed, and the builder follows no candidate. // number is needed, and the builder follows no candidate.
// BuildStep builds the entries of the step ask ask and answers its end: passed when every entry's build is done, failed when // BuildStep builds the entries of the step ask ask and answers its end: passed when every entry's build is done, failed when
// one failed (said), could not run when an entry could not be read, nothing to run for an ask naming none. The node is the // one failed (said), superseded when none failed and a newer entry of its branch superseded one (H-A-508), could not run when
// an entry could not be read, nothing to run for an ask naming none. The node is the
// caller's to set. // caller's to set.
func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.StepRun) meshbuilds.StepEnded { func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.StepRun) meshbuilds.StepEnded {
b.init() b.init()
started := b.now() started := b.now()
end := meshbuilds.StepEnded{V: 1, ID: ask, Pipeline: run.Pipeline, Step: meshbuilds.StepEndedStepBuild, Rerun: run.Rerun, By: run.By, Entries: run.Entries, Node: b.Node, Started: &started} end := meshbuilds.StepEnded{V: 1, Form: meshbuilds.Form, ID: ask, Pipeline: run.Pipeline, Step: meshbuilds.StepEndedStepBuild, Rerun: run.Rerun, By: run.By, Entries: run.Entries, Node: b.Node, Started: &started}
// finish is the one place the ask is answered: one journal line, "answered <ask> <pipeline> <movers> <step> <outcome>" // finish is the one place the ask is answered: one journal line, "answered <ask> <pipeline> <movers> <step> <outcome>"
// (design 47 H2 §792; H-A-320 (1), H-A-333). // (design 47 H2 §792; H-A-320 (1), H-A-333).
finish := func(outcome, said string) meshbuilds.StepEnded { finish := func(outcome, said string) meshbuilds.StepEnded {
@@ -33,6 +34,9 @@ func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.Step
} }
at := b.now() at := b.now()
end.Ended, end.Outcome, end.Said = &at, outcome, said end.Ended, end.Outcome, end.Said = &at, outcome, said
if outcome != meshbuilds.StepEndedOutcomeSuperseded {
end.Revision = 0
}
movers := make([]string, 0, len(run.Entries)) movers := make([]string, 0, len(run.Entries))
for _, e := range run.Entries { for _, e := range run.Entries {
movers = append(movers, e.Module) movers = append(movers, e.Module)
@@ -55,10 +59,12 @@ func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.Step
} }
// The version is reserved before the build (H-A-155): the ask waits for the builder's picture to hold its revision. // The version is reserved before the build (H-A-155): the ask waits for the builder's picture to hold its revision.
if outcome, said := b.awaitRevision(ctx, run); outcome != "" { if outcome, said := b.awaitRevision(ctx, run); outcome != "" {
// Superseded here, the catalog's revision the ask named names the superseding fingerprint (H-A-561).
end.Revision = run.Revision
return finish(outcome, said) return finish(outcome, said)
} }
b.askedRevision(run) b.askedRevision(run)
var failed []string var failed, superseded []string
for _, e := range run.Entries { for _, e := range run.Entries {
var pins map[string]string var pins map[string]string
outcome, said := b.buildEntry(ctx, run.Pipeline, e, &pins) outcome, said := b.buildEntry(ctx, run.Pipeline, e, &pins)
@@ -77,14 +83,37 @@ func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.Step
return finish(outcome, said) return finish(outcome, said)
case meshbuilds.StepEndedOutcomeFailed: case meshbuilds.StepEndedOutcomeFailed:
failed = append(failed, said) failed = append(failed, said)
case meshbuilds.StepEndedOutcomeSuperseded:
superseded = append(superseded, said)
// The end names the module graph revision of the entry that superseded it, the newest of its entries' (H-A-561).
end.Revision = max(end.Revision, b.supersedingRevision(e.Module, e.Fingerprint))
} }
} }
if len(failed) > 0 { if len(failed) > 0 {
return finish(meshbuilds.StepEndedOutcomeFailed, strings.Join(failed, "; ")) return finish(meshbuilds.StepEndedOutcomeFailed, strings.Join(failed, "; "))
} }
if len(superseded) > 0 {
return finish(meshbuilds.StepEndedOutcomeSuperseded, strings.Join(superseded, "; "))
}
return finish(meshbuilds.StepEndedOutcomePassed, "") return finish(meshbuilds.StepEndedOutcomePassed, "")
} }
// supersedingRevision is the module graph revision of the entry heard newest on the branch of module's fingerprint fp, the
// one that supersedes it (H-A-561); 0 when the picture names none.
func (b *Builder) supersedingRevision(module, fp string) int64 {
key, err := builds.BuilderBuildKey(module, fp)
if err != nil {
return 0
}
b.mu.Lock()
defer b.mu.Unlock()
o, ok := b.origin[key]
if !ok {
o = Origin{First: true}
}
return b.heardAt[o.Branch+"\x00"+module].Revision
}
// askedRevision records on the origin of each entry of run the catalog revision the ask names (design 47 H H-A-218), where // askedRevision records on the origin of each entry of run the catalog revision the ask names (design 47 H H-A-218), where
// the origin is of the ask's branch and source revision: the version reserved for its build names it, and so does its // the origin is of the ask's branch and source revision: the version reserved for its build names it, and so does its
// package-published, so the runner finds the publishing pipeline by branch and revision. // package-published, so the runner finds the publishing pipeline by branch and revision.
@@ -117,8 +146,9 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds.
if entry.Module != e.Module || (e.Commit != "" && entry.Commit != e.Commit) { if entry.Module != e.Module || (e.Commit != "" && entry.Commit != e.Commit) {
return meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the entry of %s at %s is of %s at %s", e.Module, e.Fingerprint, entry.Module, entry.Commit) return meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the entry of %s at %s is of %s at %s", e.Module, e.Fingerprint, entry.Module, entry.Commit)
} }
// A package the entry names with no pin is built against its publish, waited for (H-A-192, H-A-165). // A package the entry names with no pin is built against its publisher's version at the key's origin, waited for
pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, meshcatalogclient.BareManifestDigest(entry.ManifestDigest), entry.Packages) // (H-A-521, H-A-547 (3), H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, entry.Packages)
if outcome != "" { if outcome != "" {
return outcome, said return outcome, said
} }
@@ -133,7 +163,19 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds.
b.logf("%s@%s build step answered %s for %s (%s)", entry.Module, entry.Fp, outcome, pipeline, how) b.logf("%s@%s build step answered %s for %s (%s)", entry.Module, entry.Fp, outcome, pipeline, how)
return outcome, said return outcome, said
} }
if done, failedWords, found := b.keyEnd(ctx, key); found { done, failedWords, found := b.keyEnd(ctx, key)
// The fingerprint is judged against its branch's newest entry first, for a done build as for one not built (H-A-508): a
// superseded one ends the step superseded, naming the superseding fingerprint, never failed. One not built is refused, not
// waited on (H-A-489): no look builds a superseded fingerprint, so its end would never come.
if newer := b.supersededBy(entry.Module, key, entry.Fp); newer != "" {
how := "existing build"
if !found {
how = "refused"
b.saySuperseded(entry.Module, key, entry.Fp, newer)
}
return answered(meshbuilds.StepEndedOutcomeSuperseded, stepSuperseded(entry.Module, entry.Fp, newer), how)
}
if found {
if done { if done {
// A key done before reports the pins it was built with, kept with it, never the ones a publish gives now. // A key done before reports the pins it was built with, kept with it, never the ones a publish gives now.
*pins = b.keptPins(ctx, key) *pins = b.keptPins(ctx, key)
@@ -147,6 +189,11 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds.
b.consider(ctx, entry.Module, m) b.consider(ctx, entry.Module, m)
select { select {
case log := <-ended: case log := <-ended:
// A fingerprint a newer entry superseded while it built (its build withdrawn, or done) ends superseded, judged before
// the log's outcome (H-A-508).
if newer := b.supersededBy(entry.Module, key, entry.Fp); newer != "" {
return answered(meshbuilds.StepEndedOutcomeSuperseded, stepSuperseded(entry.Module, entry.Fp, newer), "built now")
}
if log.Outcome == builds.BuildDone { if log.Outcome == builds.BuildDone {
*pins = b.keptPins(ctx, key) *pins = b.keptPins(ctx, key)
outcome, said := b.passedWithItsVersion(ctx, entry) outcome, said := b.passedWithItsVersion(ctx, entry)
@@ -164,13 +211,18 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds.
// that can never be released, and one whose series another fingerprint took over fails saying it is stale, naming that // that can never be released, and one whose series another fingerprint took over fails saying it is stale, naming that
// fingerprint and its version (design 47 H H-A-244). A build that reserves none (a candidate's, a series of before G) passes as it did. // fingerprint and its version (design 47 H H-A-244). A build that reserves none (a candidate's, a series of before G) passes as it did.
func (b *Builder) passedWithItsVersion(ctx context.Context, entry meshcatalog.CatalogEntry) (outcome, said string) { func (b *Builder) passedWithItsVersion(ctx context.Context, entry meshcatalog.CatalogEntry) (outcome, said string) {
if b.Reserved == nil {
return meshbuilds.StepEndedOutcomePassed, ""
}
key, err := builds.BuilderBuildKey(entry.Module, entry.Fp) key, err := builds.BuilderBuildKey(entry.Module, entry.Fp)
if err != nil { if err != nil {
return meshbuilds.StepEndedOutcomeCouldNotRun, err.Error() return meshbuilds.StepEndedOutcomeCouldNotRun, err.Error()
} }
// The fingerprint is judged against its branch's newest entry first (H-A-508): a superseded one ends superseded, whatever
// its reservation, release or takeover says.
if newer := b.supersededBy(entry.Module, key, entry.Fp); newer != "" {
return meshbuilds.StepEndedOutcomeSuperseded, stepSuperseded(entry.Module, entry.Fp, newer)
}
if b.Reserved == nil {
return meshbuilds.StepEndedOutcomePassed, ""
}
b.mu.Lock() b.mu.Lock()
reserving := b.trunkFP[key] && b.origin[key].First reserving := b.trunkFP[key] && b.origin[key].First
b.mu.Unlock() b.mu.Unlock()
@@ -205,6 +257,11 @@ func (b *Builder) passedWithItsVersion(ctx context.Context, entry meshcatalog.Ca
return meshbuilds.StepEndedOutcomePassed, "" return meshbuilds.StepEndedOutcomePassed, ""
} }
// stepSuperseded is the why of a build step ended superseded (H-A-508): the fingerprint and the newer entry that superseded it.
func stepSuperseded(module, fp, newer string) string {
return fmt.Sprintf("%s at %s is superseded by %s, the newest entry heard on its first branch", module, fp, newer)
}
// keptPins are the pins a done key keeps it was built with (H-A-207); none when it keeps none or cannot be read, so the // keptPins are the pins a done key keeps it was built with (H-A-207); none when it keeps none or cannot be read, so the
// runner ends the steps that waited for them could not run, loud. // runner ends the steps that waited for them could not run, loud.
func (b *Builder) keptPins(ctx context.Context, key string) map[string]string { func (b *Builder) keptPins(ctx context.Context, key string) map[string]string {
@@ -232,7 +289,7 @@ func (b *Builder) keyEnd(ctx context.Context, key string) (done bool, failed str
switch { switch {
case v.State == builds.BuildDone && !Unpublished(v, b.Seats): case v.State == builds.BuildDone && !Unpublished(v, b.Seats):
return true, "", true return true, "", true
case v.State == builds.BuildFailed && builds.FailedUntilChanged(v.Error): case v.State == builds.BuildFailed && (builds.FailedUntilChanged(v.Error) || strings.HasPrefix(v.Error, withdrawnPrefix)):
return false, key + ": " + v.Error, true return false, key + ": " + v.Error, true
} }
return false, "", false return false, "", false
@@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"reflect" "reflect"
"runtime"
"slices" "slices"
"strings" "strings"
"sync" "sync"
@@ -12,7 +13,9 @@ import (
"testing" "testing"
"time" "time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -74,6 +77,21 @@ func TestABuildStepAnswersItsEnd(t *testing.T) {
if end := ask(entries...); end.Outcome != meshbuilds.StepEndedOutcomePassed || end.Step != meshbuilds.StepEndedStepBuild || len(end.Entries) != 1 || end.Entries[0].Commit != "c1" || end.Pipeline != "main.1.m" { if end := ask(entries...); end.Outcome != meshbuilds.StepEndedOutcomePassed || end.Step != meshbuilds.StepEndedStepBuild || len(end.Entries) != 1 || end.Entries[0].Commit != "c1" || end.Pipeline != "main.1.m" {
t.Errorf("a done build: %+v", end) t.Errorf("a done build: %+v", end)
} }
// H-A-489 (review round 1): a withdrawn key whose fingerprint is still the newest entry is answered failed at once, naming
// withdrawn: no look builds it again, so its end is never waited for.
rw := newRig(t, catalogue.Artifact{Name: "files", Kind: "archive"})
rw.b.StepEntry = r.b.StepEntry
withdrawn, _ := builds.EncodeBuilderBuild(builds.BuilderBuild{State: builds.BuildFailed, Manifest: mdigest('a'), Error: withdrawnPrefix + "its reservation 0.1.3 was taken over"})
if _, err := rw.st.Create(t.Context(), rw.key, withdrawn); err != nil {
t.Fatal(err)
}
rw.b.Module(t.Context(), "m", moduleValue(t, "modules/m")) // the newest entry heard is fp1
rw.b.Wait()
bounded, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
if end := rw.b.BuildStep(bounded, "ask1", meshbuilds.StepRun{Pipeline: "main.1.m", Step: meshbuilds.StepRunStepBuild, Entries: entries}); end.Outcome != meshbuilds.StepEndedOutcomeFailed || !strings.Contains(end.Said, "withdrawn: ") {
t.Errorf("a withdrawn key asked: %+v, want failed at once naming withdrawn", end)
}
} }
// A step ask waits for the end of its build without a timer: the log entry of that end wakes it (design 47 G A-97). // A step ask waits for the end of its build without a timer: the log entry of that end wakes it (design 47 G A-97).
@@ -109,26 +127,40 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T)
for _, c := range []struct { for _, c := range []struct {
name, version string name, version string
reserve, released, unreadable bool reserve, released, unreadable bool
takenOver bool takenOver, superseded bool
want, said string want, said string
}{ }{
{"no version reserved", "0.1", false, false, false, false, meshbuilds.StepEndedOutcomeFailed, "built at " + fp1 + ", but no version is reserved for it"}, {"no version reserved", "0.1", false, false, false, false, false, meshbuilds.StepEndedOutcomeFailed, "built at " + fp1 + ", but no version is reserved for it"},
{"H-A-244: its series was taken over by a newer fingerprint", "0.1", false, false, false, true, meshbuilds.StepEndedOutcomeFailed, "m: built at " + fp1 + " but its series moved to " + fp2 + " 0.1.7: stale"}, {"H-A-244: its series was taken over by a newer fingerprint", "0.1", false, false, false, true, false, meshbuilds.StepEndedOutcomeFailed, "m: built at " + fp1 + " but its series moved to " + fp2 + " 0.1.7: stale"},
{"a version reserved", "0.1", true, false, false, false, meshbuilds.StepEndedOutcomePassed, ""}, // H-A-508: a done build a newer entry of its branch superseded is judged against that entry first, its takeover lost
{"a released build whose reservation is gone", "0.1", false, true, false, false, meshbuilds.StepEndedOutcomePassed, ""}, // with the release that deleted it: superseded, naming the newer fingerprint, never "no version is reserved".
{"the plan cannot be read", "0.1", false, false, true, false, meshbuilds.StepEndedOutcomeCouldNotRun, "plan cannot be read"}, {"H-A-508: a done build a newer entry superseded", "0.1", false, false, false, false, true, meshbuilds.StepEndedOutcomeSuperseded, "m at " + fp1 + " is superseded by " + fp2},
{"a series of before G", "1", false, false, false, false, meshbuilds.StepEndedOutcomePassed, ""}, {"H-A-508: a done build a newer entry superseded, though a version is reserved", "0.1", true, false, false, false, true, meshbuilds.StepEndedOutcomeSuperseded, "m at " + fp1 + " is superseded by " + fp2},
{"H-A-508: a done build a newer entry superseded, its series taken over", "0.1", false, false, false, true, true, meshbuilds.StepEndedOutcomeSuperseded, "m at " + fp1 + " is superseded by " + fp2},
{"a version reserved", "0.1", true, false, false, false, false, meshbuilds.StepEndedOutcomePassed, ""},
{"a released build whose reservation is gone", "0.1", false, true, false, false, false, meshbuilds.StepEndedOutcomePassed, ""},
{"the plan cannot be read", "0.1", false, false, true, false, false, meshbuilds.StepEndedOutcomeCouldNotRun, "plan cannot be read"},
{"a series of before G", "1", false, false, false, false, false, meshbuilds.StepEndedOutcomePassed, ""},
} { } {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.version, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.version, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true, released: map[string]bool{fp1: c.released}} res := &fakeReservations{released: map[string]bool{fp1: c.released}}
if c.takenOver { if c.takenOver {
res.tookBy = map[string]versions.ReservedVersion{fp1: {Module: "m", Series: "0.1", Version: "0.1.7", Fingerprint: fp2}} res.tookBy = map[string]versions.ReservedVersion{fp1: {Module: "m", Series: "0.1", Version: "0.1.7", Fingerprint: fp2}}
} }
if v := r.consider(t, "modules/m"); v.State != builds.BuildDone { // built while the builder reserved nothing, as the live key was if v := r.consider(t, "modules/m"); v.State != builds.BuildDone { // built while the builder reserved nothing, as the live key was
t.Fatalf("build = %+v, want done", v) t.Fatalf("build = %+v, want done", v)
} }
if c.superseded { // a newer entry of the branch heard after the build
newer, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp2: fp2, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)})
if err != nil {
t.Fatal(err)
}
r.b.Module(t.Context(), "m", newer)
r.b.Wait()
}
r.b.Reserved = res r.b.Reserved = res
if c.reserve { if c.reserve {
res.sources = append(res.sources, versions.Source{Fingerprint: fp1}) res.sources = append(res.sources, versions.Source{Fingerprint: fp1})
@@ -140,26 +172,42 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T)
if end.Outcome != c.want || !strings.Contains(end.Said, c.said) || (c.want == meshbuilds.StepEndedOutcomeFailed && strings.Contains(end.Said, "builder_reserve_done") == c.takenOver) { if end.Outcome != c.want || !strings.Contains(end.Said, c.said) || (c.want == meshbuilds.StepEndedOutcomeFailed && strings.Contains(end.Said, "builder_reserve_done") == c.takenOver) {
t.Errorf("end = %+v, want %s saying %q", end, c.want, c.said) t.Errorf("end = %+v, want %s saying %q", end, c.want, c.said)
} }
// The verdict of a build that ended done, as a build ended now is judged, says the same (H-A-508: the newest entry first).
if c.superseded {
entry, _ := r.b.StepEntry(t.Context(), fp1)
if outcome, said := r.b.passedWithItsVersion(t.Context(), entry); outcome != c.want || !strings.Contains(said, c.said) {
t.Errorf("built now: %s %q, want %s saying %q", outcome, said, c.want, c.said)
}
}
}) })
} }
t.Run("H-A-508: built now, superseded: a newer entry heard while the build runs ends the step superseded", aNewerEntryWhileTheBuildRunsSupersedesTheStep)
t.Run("H-A-155: an ask waits for the picture to take its revision in, then builds with its version reserved", aStepAskWaitsForItsRevision) t.Run("H-A-155: an ask waits for the picture to take its revision in, then builds with its version reserved", aStepAskWaitsForItsRevision)
t.Run("H-A-155: past the bound the ask fails naming its revision, and nothing is built", aStepAskPastItsRevisionBoundFails) t.Run("H-A-155: past the bound the ask fails naming its revision, and nothing is built", aStepAskPastItsRevisionBoundFails)
t.Run("H-A-205: an ask of a revision below the picture's newest is read by number and built", anOlderKeptRevisionIsReadByNumber) t.Run("H-A-205: an ask of a revision below the picture's newest is read by number and built", anOlderKeptRevisionIsReadByNumber)
t.Run("H-A-557: an entry the picture heard of an older revision supersedes no ask of a newer one", anOlderHeardEntrySupersedesNoNewerAsk)
t.Run("H-A-557: an entry heard of an older revision withdraws no running build of a newer one", anOlderHeardEntryWithdrawsNoNewerBuild)
t.Run("H-A-162: a revision held that changes no entry wakes the ask", aRevisionHeldWakesTheAsk) t.Run("H-A-162: a revision held that changes no entry wakes the ask", aRevisionHeldWakesTheAsk)
t.Run("H-A-165: a package with no pin waits for its release and is built with it", aPackageWithNoPinWaitsForItsRelease) t.Run("H-A-547 (3): a package with no pin waits for its publisher's version at the key's origin and is built with it", aPackageWithNoPinWaitsForItsRelease)
t.Run("H-A-165: past its bound a package with no release fails the step", aPackageWithNoReleaseFailsPastItsBound) t.Run("H-A-165: past its bound a package with no version at the origin fails the step", aPackageWithNoReleaseFailsPastItsBound)
t.Run("H-A-192: a lane waits for an unpinned package's publish and fails past its bound", aLaneWaitsForAnUnpinnedPackage) t.Run("H-A-547 (3): a lane waits for an unpinned package's version at its origin and fails past its bound", aLaneWaitsForAnUnpinnedPackage)
t.Run("H-A-194: what the registry seat holds pins the package before any wait", theSeatsVersionsPinBeforeTheWait)
} }
// unpinnedRig is a rig whose step entry m names the package x with no version. Its manifest names no `packages`, so it // unpinnedRig is a rig whose step entry m names the package x with no version, x published by the artifact x of the module xm,
// accepts x in the default series 0.1. waiting is told when a build starts its wait for a package's publish. // its key's origin source revision 41 of main. waiting is told when a build starts its wait for a package's publish.
func unpinnedRig(t *testing.T) (*rig, meshcatalog.CatalogEntry, <-chan struct{}) { func unpinnedRig(t *testing.T) (*rig, *fakeReservations, meshcatalog.CatalogEntry, <-chan struct{}) {
var held atomic.Int64 var held atomic.Int64
r, _, entry := revisionRig(t, &held, make(chan struct{}, 1)) r, res, entry := revisionRig(t, &held, make(chan struct{}, 1))
r.b.Picture = nil // no revision to wait for here r.b.Picture = nil // no revision to wait for here
entry.Packages = map[string]string{unpinnedX: "", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"} entry.Packages = map[string]string{unpinnedX: "", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"}
r.b.StepEntry = func(context.Context, string) (meshcatalog.CatalogEntry, error) { return entry, nil } r.b.StepEntry = func(context.Context, string) (meshcatalog.CatalogEntry, error) { return entry, nil }
r.b.Members = func(_ context.Context, pkg string) (string, string, bool, error) {
return "xm", "x", pkg == unpinnedX, nil
}
r.b.init()
r.b.mu.Lock()
r.b.origin[r.key] = Origin{Branch: "main", Source: 41, First: true}
r.b.mu.Unlock()
waiting := make(chan struct{}, 1) waiting := make(chan struct{}, 1)
r.b.Logf = func(format string, args ...any) { r.b.Logf = func(format string, args ...any) {
t.Logf(format, args...) t.Logf(format, args...)
@@ -170,7 +218,7 @@ func unpinnedRig(t *testing.T) (*rig, meshcatalog.CatalogEntry, <-chan struct{})
} }
} }
} }
return r, entry, waiting return r, res, entry, waiting
} }
const unpinnedX = "git.novox.be/novox/mesh-contracts/go/seats/x" const unpinnedX = "git.novox.be/novox/mesh-contracts/go/seats/x"
@@ -187,10 +235,10 @@ func awaitWaiting[T any](t *testing.T, waiting <-chan struct{}, ended <-chan T)
} }
} }
// H-A-192: the pin is the version the registry seat's published carries for the path in the accepted series; a publish in // H-A-547 (3), H-A-551: the pin is the version the module publishing the package holds at the source revision of the key's
// another series and the module's release number pin nothing. // origin; a version of another source revision and the newest a registry seat said published pin nothing.
func aPackageWithNoPinWaitsForItsRelease(t *testing.T) { func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
r, _, waiting := unpinnedRig(t) r, res, _, waiting := unpinnedRig(t)
// Each entry's answer from a build is one journal line, built now or existing, beside the ask's answer (H-A-320 (1), H-A-333). // Each entry's answer from a build is one journal line, built now or existing, beside the ask's answer (H-A-320 (1), H-A-333).
var mu sync.Mutex var mu sync.Mutex
var answers []string var answers []string
@@ -203,8 +251,8 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
mu.Unlock() mu.Unlock()
} }
} }
r.b.PackagePublished(unpinnedX, "v0.2.9") // another series than the 0.1 the module accepts: no pin res.publishAt("xm", "x", "main", 40, "0.1.2") // another source revision than the key's origin: no pin
r.b.PackagePublished(unpinnedX, "0.1.4-feat-x.2") // a group's tagged version: no pin r.b.PackagePublished(unpinnedX, "v0.1.9") // the newest heard: no pin (H-A-547 (3))
ended := make(chan meshbuilds.StepEnded, 1) ended := make(chan meshbuilds.StepEnded, 1)
go func() { go func() {
ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
@@ -214,6 +262,7 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
if _, ok := r.st.vals[r.key]; ok { if _, ok := r.st.vals[r.key]; ok {
t.Fatal("the build was made before the package was published") t.Fatal("the build was made before the package was published")
} }
res.publishAt("xm", "x", "main", 41, "0.1.3")
r.b.PackagePublished(unpinnedX, "v0.1.3") r.b.PackagePublished(unpinnedX, "v0.1.3")
var end meshbuilds.StepEnded var end meshbuilds.StepEnded
select { select {
@@ -231,8 +280,8 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
if !reflect.DeepEqual(end.Packages, map[string]string{unpinnedX: "v0.1.3", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"}) { if !reflect.DeepEqual(end.Packages, map[string]string{unpinnedX: "v0.1.3", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"}) {
t.Errorf("the end reports the pins %v; want the ones it was built with", end.Packages) t.Errorf("the end reports the pins %v; want the ones it was built with", end.Packages)
} }
// A done key reports the pins it keeps it was built with, never the newer one a publish gives now (H-A-207). // A done key reports the pins it keeps it was built with, never a newer one published now (H-A-207).
r.b.PackagePublished(unpinnedX, "v0.1.5") res.publishAt("xm", "x", "main", 41, "0.1.5")
again := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, again := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
if again.Outcome != meshbuilds.StepEndedOutcomePassed || again.Packages[unpinnedX] != "v0.1.3" { if again.Outcome != meshbuilds.StepEndedOutcomePassed || again.Packages[unpinnedX] != "v0.1.3" {
@@ -262,59 +311,27 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
} }
func aPackageWithNoReleaseFailsPastItsBound(t *testing.T) { func aPackageWithNoReleaseFailsPastItsBound(t *testing.T) {
r, _, _ := unpinnedRig(t) r, res, _, _ := unpinnedRig(t)
r.b.PackageWait = time.Nanosecond r.b.PackageWait = time.Nanosecond
end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
r.b.Wait() r.b.Wait()
if _, built := r.st.vals[r.key]; end.Outcome != meshbuilds.StepEndedOutcomeFailed || built || if _, built := r.st.vals[r.key]; end.Outcome != meshbuilds.StepEndedOutcomeFailed || built ||
!strings.Contains(end.Said, "package "+unpinnedX+" has no released version in the series 0.1") { !strings.Contains(end.Said, "package "+unpinnedX+" has no published version: xm publishes no version of it at source revision 41 of main") {
t.Errorf("end = %+v, built %v; want failed naming the package, nothing built", end, built) t.Errorf("end = %+v, built %v; want failed naming the package, nothing built", end, built)
} }
// A publish heard before gives the pin at once. // A version its publisher holds at the origin gives the pin at once.
r.b.PackagePublished(unpinnedX, "v0.1.2") res.publishAt("xm", "x", "main", 41, "0.1.2")
if end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, if end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}); strings.Contains(end.Said, "no released version") { Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}); strings.Contains(end.Said, "no published version") {
t.Errorf("a publish heard did not pin the package: %+v", end) t.Errorf("a version at the origin did not pin the package: %+v", end)
} }
} }
// H-A-194: the build reads the registry seat's versions of the path once before it waits: a version in the accepted series // H-A-547 (3), H-A-165: the lane of an entry taken in waits the same way, never asking a build without the pin, and fails the
// pins the package with no event heard; one only in another series leaves the build waiting for a publish.
func theSeatsVersionsPinBeforeTheWait(t *testing.T) {
r, _, _ := unpinnedRig(t)
r.b.PackageWait = time.Nanosecond // no wait: the seat's answer alone gives the pin
var read []string
r.b.PublishedVersions = func(_ context.Context, path string) ([]string, error) {
read = append(read, path)
return []string{"0.2.1", "0.1.9", "0.1.8"}, nil // newest first
}
end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
r.b.Wait()
asks := r.asks.Asks()
if end.Outcome != meshbuilds.StepEndedOutcomePassed || len(asks) == 0 || asks[0].Packages[unpinnedX] != "v0.1.9" || !slices.Equal(read, []string{unpinnedX}) {
t.Errorf("end = %+v, asks %+v, read %v; want passed, built with x at v0.1.9 read once from the seat", end, asks, read)
}
r2, _, waiting := unpinnedRig(t)
r2.b.PublishedVersions = func(context.Context, string) ([]string, error) { return []string{"0.2.1"}, nil }
ended := make(chan meshbuilds.StepEnded, 1)
go func() {
ended <- r2.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
}()
awaitWaiting(t, waiting, ended)
r2.b.PackagePublished(unpinnedX, "0.1.10")
if end := <-ended; end.Outcome != meshbuilds.StepEndedOutcomePassed {
t.Errorf("end = %+v, want passed once x was published in its series", end)
}
r2.b.Wait()
}
// H-A-192, H-A-165: the lane of an entry taken in waits the same way, never asking a build without the pin, and fails the
// key past the bound naming the package. // key past the bound naming the package.
func aLaneWaitsForAnUnpinnedPackage(t *testing.T) { func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
r, entry, waiting := unpinnedRig(t) r, res, entry, waiting := unpinnedRig(t)
done := make(chan struct{}) done := make(chan struct{})
go func() { go func() {
r.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry) r.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry)
@@ -325,6 +342,7 @@ func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
if asks := r.asks.Asks(); len(asks) != 0 { if asks := r.asks.Asks(); len(asks) != 0 {
t.Fatalf("a build was asked without the package's pin: %+v", asks) t.Fatalf("a build was asked without the package's pin: %+v", asks)
} }
res.publishAt("xm", "x", "main", 41, "0.1.5")
r.b.PackagePublished(unpinnedX, "0.1.5") r.b.PackagePublished(unpinnedX, "0.1.5")
select { select {
case <-done: case <-done:
@@ -335,11 +353,11 @@ func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
t.Errorf("asks %+v; want one asked with x at v0.1.5", asks) t.Errorf("asks %+v; want one asked with x at v0.1.5", asks)
} }
// Past its bound the key fails naming the package, and nothing is asked. // Past its bound the key fails naming the package, and nothing is asked.
r2, entry2, _ := unpinnedRig(t) r2, _, entry2, _ := unpinnedRig(t)
r2.b.PackageWait = time.Nanosecond r2.b.PackageWait = time.Nanosecond
r2.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry2) r2.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry2)
r2.b.Wait() r2.b.Wait()
if asks := r2.asks.Asks(); len(asks) != 0 || !strings.Contains(string(r2.st.vals[r2.key]), "package "+unpinnedX+" has no released version") { if asks := r2.asks.Asks(); len(asks) != 0 || !strings.Contains(string(r2.st.vals[r2.key]), "package "+unpinnedX+" has no published version") {
t.Errorf("asks %+v, key %s; want none asked and the key failed naming the package", asks, r2.st.vals[r2.key]) t.Errorf("asks %+v, key %s; want none asked and the key failed naming the package", asks, r2.st.vals[r2.key])
} }
} }
@@ -379,7 +397,7 @@ func aRevisionHeldWakesTheAsk(t *testing.T) {
func revisionRig(t *testing.T, held *atomic.Int64, asked chan struct{}) (*rig, *fakeReservations, meshcatalog.CatalogEntry) { func revisionRig(t *testing.T, held *atomic.Int64, asked chan struct{}) (*rig, *fakeReservations, meshcatalog.CatalogEntry) {
r := newRig(t, goBundle) r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true} res := &fakeReservations{}
r.b.Reserved = res r.b.Reserved = res
entry := meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1, entry := meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1,
ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}} ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}}
@@ -434,9 +452,10 @@ func aStepAskWaitsForItsRevision(t *testing.T) {
} }
// H-A-205: two pipelines of consecutive revisions run at once; the picture holds source revision 46, whose entry of m moved // H-A-205: two pipelines of consecutive revisions run at once; the picture holds source revision 46, while the older pipeline
// on, while the older pipeline asks the build of revision 45. Its kept catalog revision is read by number and the build runs; // asks the build of revision 45. Its kept catalog revision is read by number and the build runs while the picture never heard
// a kept revision naming another fingerprint fails the step, naming it. // a newer entry of m (a restart); once it heard one on the first branch, H-A-489 overrides H-A-205 and the older ask is refused
// superseded. A kept revision naming another fingerprint ends the step superseded, naming it (H-A-508 second addendum).
func anOlderKeptRevisionIsReadByNumber(t *testing.T) { func anOlderKeptRevisionIsReadByNumber(t *testing.T) {
var held atomic.Int64 var held atomic.Int64
held.Store(46) held.Store(46)
@@ -460,13 +479,34 @@ func anOlderKeptRevisionIsReadByNumber(t *testing.T) {
if len(res.sources) != 1 || res.sources[0].Revision != 45 || res.sources[0].CatalogRevision != 47 { if len(res.sources) != 1 || res.sources[0].Revision != 45 || res.sources[0].CatalogRevision != 47 {
t.Errorf("reserved from %+v; want one version reserved from source revision 45 at catalog revision 47 (H-A-218)", res.sources) t.Errorf("reserved from %+v; want one version reserved from source revision 45 at catalog revision 47 (H-A-218)", res.sources)
} }
// H-A-489, H-A-508: once the picture heard the newer entry of m on the first branch, the older ask ends superseded (never
// failed) and nothing is built or reserved for it; the newer entry's build keeps the series.
rn, resn, entryn := revisionRig(t, &held, make(chan struct{}, 1))
rn.b.RevisionWait = time.Nanosecond
rn.b.FirstBranch = r.b.FirstBranch
rn.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) {
return 45, map[string]string{"m": fp1}, nil
}
entryn.Fp = fp2
rn.b.Entry(context.Background(), Origin{Branch: "main", Source: 46, First: true}, entryn)
rn.b.Wait()
if endn := rn.b.BuildStep(t.Context(), "a1", run); endn.Outcome != meshbuilds.StepEndedOutcomeSuperseded || !strings.Contains(endn.Said, "superseded by "+fp2) {
t.Errorf("the older ask after the newer entry: end = %+v; want superseded by %s", endn, fp2)
}
rn.b.Wait()
if _, built := rn.st.vals[rn.key]; built || len(resn.sources) != 1 || resn.sources[0].Fingerprint != fp2 {
t.Errorf("built %v, reserved %+v; want nothing built for the older, one reservation, the newer's", built, resn.sources)
}
r2, _, _ := revisionRig(t, &held, make(chan struct{}, 1)) r2, _, _ := revisionRig(t, &held, make(chan struct{}, 1))
r2.b.RevisionWait = time.Nanosecond r2.b.RevisionWait = time.Nanosecond
r2.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) { r2.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) {
return 45, map[string]string{"m": "src2:other"}, nil return 45, map[string]string{"m": "src2:other"}, nil
} }
if end := r2.b.BuildStep(t.Context(), "a1", run); end.Outcome != meshbuilds.StepEndedOutcomeFailed || !strings.Contains(end.Said, "names m at \"src2:other\"") { // H-A-508 second addendum: below the picture, a kept revision naming another fingerprint of the module superseded the
t.Errorf("end = %+v; want failed naming the fingerprint the kept revision names", end) // ask's: the step ends superseded naming it, never failed with the "below" words.
// H-A-561: the end names the catalog's revision that names the superseding fingerprint, the ask's own.
if end := r2.b.BuildStep(t.Context(), "a1", run); end.Outcome != meshbuilds.StepEndedOutcomeSuperseded || end.Said != stepSuperseded("m", fp1, "src2:other") || end.Revision != 47 {
t.Errorf("end = %+v; want superseded naming the fingerprint the kept revision names", end)
} }
// H-A-222: an ask of the very source the picture holds, whose entries the picture no longer names (a re-pin kept revision 48 // H-A-222: an ask of the very source the picture holds, whose entries the picture no longer names (a re-pin kept revision 48
// of the same source 46 and the picture took its entries in), is held by its revision read by number, never waited for. // of the same source 46 and the picture took its entries in), is held by its revision read by number, never waited for.
@@ -485,7 +525,7 @@ func anOlderKeptRevisionIsReadByNumber(t *testing.T) {
if end3.Outcome != meshbuilds.StepEndedOutcomePassed || !slices.Equal(read3, []string{"main 48"}) || len(res3.sources) != 1 || res3.sources[0].CatalogRevision != 48 { if end3.Outcome != meshbuilds.StepEndedOutcomePassed || !slices.Equal(read3, []string{"main 48"}) || len(res3.sources) != 1 || res3.sources[0].CatalogRevision != 48 {
t.Errorf("end = %+v, kept revisions read %v, reserved %+v; want passed, revision 48 of main read once and reserved at it", end3, read3, res3.sources) t.Errorf("end = %+v, kept revisions read %v, reserved %+v; want passed, revision 48 of main read once and reserved at it", end3, read3, res3.sources)
} }
// H-A-218, H-A-222: a kept revision of another source than the ask names, or naming another fingerprint, is a mismatch: // H-A-218, H-A-222: a kept revision of another source than the ask names is a mismatch:
// the step fails at once naming it, never waiting out its bound (the bound here is long, the ask is not below the picture). // the step fails at once naming it, never waiting out its bound (the bound here is long, the ask is not below the picture).
for _, c := range []struct { for _, c := range []struct {
name string name string
@@ -494,7 +534,6 @@ func anOlderKeptRevisionIsReadByNumber(t *testing.T) {
said string said string
}{ }{
{"another source", 45, fp1, "the catalog's revision 48 is of source revision 45, the ask names 46"}, {"another source", 45, fp1, "the catalog's revision 48 is of source revision 45, the ask names 46"},
{"another fingerprint", 46, "src2:other", "names m at \"src2:other\""},
} { } {
rc, resc, _ := revisionRig(t, &held, make(chan struct{}, 1)) rc, resc, _ := revisionRig(t, &held, make(chan struct{}, 1))
rc.b.RevisionWait = time.Hour rc.b.RevisionWait = time.Hour
@@ -507,6 +546,96 @@ func anOlderKeptRevisionIsReadByNumber(t *testing.T) {
t.Errorf("%s: end = %+v, reserved %+v; want failed at once saying %q, nothing reserved", c.name, end, resc.sources, c.said) t.Errorf("%s: end = %+v, reserved %+v; want failed at once saying %q, nothing reserved", c.name, end, resc.sources, c.said)
} }
} }
// H-A-508 second addendum, found by either check: a revision read by its number (H-A-222) whose kept revision names another
// fingerprint of m superseded the ask's: it ends superseded at once naming it, never failed and never waiting its bound.
rs, ress, _ := revisionRig(t, &held, make(chan struct{}, 1))
rs.b.RevisionWait = time.Hour
rs.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) {
return 46, map[string]string{"m": "src2:other"}, nil
}
ends := rs.b.BuildStep(t.Context(), "a1", same)
rs.b.Wait()
if ends.Outcome != meshbuilds.StepEndedOutcomeSuperseded || ends.Said != stepSuperseded("m", fp1, "src2:other") || len(ress.sources) != 0 {
t.Errorf("by its number, another fingerprint: end = %+v, reserved %+v; want superseded by src2:other at once, nothing reserved", ends, ress.sources)
}
}
// H-A-557 (main.453): the picture lags the runner: it holds source revision 140, its entry of m (fp2) heard at catalog revision
// 452, while main.453's ask names fp1 at revision 453 of source 141, read by number. The older entry heard is passed over:
// the step builds and passes, never superseded by fp2.
func anOlderHeardEntrySupersedesNoNewerAsk(t *testing.T) {
var held atomic.Int64
held.Store(140)
r, res, entry := revisionRig(t, &held, make(chan struct{}, 1))
r.b.RevisionWait = time.Hour
var mu sync.Mutex
var journal []string
r.b.Logf = func(f string, a ...any) { mu.Lock(); journal = append(journal, fmt.Sprintf(f, a...)); mu.Unlock() }
r.b.FirstBranch = func(branch, module string) bool { return branch == "main" && module == "m" }
r.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) {
return 141, map[string]string{"m": fp1}, nil
}
older := entry
older.Fp = fp2
r.b.Entry(context.Background(), Origin{Branch: "main", Source: 140, Revision: 452, First: true}, older)
r.b.Wait()
run := meshbuilds.StepRun{Pipeline: "main.453.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Revision: 453, Source: 141,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}
end := r.b.BuildStep(t.Context(), "a1", run)
r.b.Wait()
if end.Outcome != meshbuilds.StepEndedOutcomePassed {
t.Errorf("end = %+v, reserved %+v; want passed: the entry heard at revision 452 supersedes no ask of revision 453", end, res.sources)
}
mu.Lock()
defer mu.Unlock()
if !slices.ContainsFunc(journal, func(l string) bool {
return strings.Contains(l, "is not of a newer revision: not superseded by it (H-A-557)")
}) {
t.Errorf("the passed-over entry is not said: %v", journal)
}
}
// H-A-557 (review round 1): the entry of m at revision 453 (fp1) is heard and its build runs; an entry of revision 452 (fp2)
// heard after it is older and withdraws nothing; one of revision 454 withdraws it, naming the newer fingerprint.
func anOlderHeardEntryWithdrawsNoNewerBuild(t *testing.T) {
var held atomic.Int64
held.Store(141)
r, _, entry := revisionRig(t, &held, make(chan struct{}, 1))
r.b.FirstBranch = func(branch, module string) bool { return branch == "main" && module == "m" }
r.b.Entry(context.Background(), Origin{Branch: "main", Source: 141, Revision: 453, First: true}, entry)
r.b.Wait()
var withdrawn []error
r.b.mu.Lock()
r.b.builds[r.key] = func(cause error) { withdrawn = append(withdrawn, cause) } // fp1's build runs
r.b.mu.Unlock()
older := entry
older.Fp = fp2
r.b.Entry(context.Background(), Origin{Branch: "main", Source: 140, Revision: 452, First: true}, older)
r.b.Wait()
if len(withdrawn) != 0 {
t.Fatalf("an entry of revision 452 withdrew the build of revision 453's fingerprint: %v", withdrawn)
}
newer := entry
newer.Fp = "src2:" + hex64('e')
r.b.Entry(context.Background(), Origin{Branch: "main", Source: 142, Revision: 454, First: true}, newer)
r.b.Wait()
if len(withdrawn) != 1 || !strings.Contains(withdrawn[0].Error(), newer.Fp) {
t.Errorf("after revision 454's entry: withdrawn %v; want fp1's build withdrawn once, naming %s", withdrawn, newer.Fp)
}
// H-A-561: a step of fp1 at revision 453 now ends superseded, naming revision 454, the superseding entry's.
r.b.mu.Lock()
delete(r.b.builds, r.key)
r.b.mu.Unlock()
r.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) {
return 141, map[string]string{"m": fp1}, nil
}
held.Store(142)
end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.453.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Revision: 453, Source: 141,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
r.b.Wait()
if end.Outcome != meshbuilds.StepEndedOutcomeSuperseded || end.Revision != 454 || !strings.Contains(end.Said, newer.Fp) {
t.Errorf("fp1's step after revision 454's entry: end = %+v; want superseded by %s, naming revision 454", end, newer.Fp)
}
} }
func aStepAskPastItsRevisionBoundFails(t *testing.T) { func aStepAskPastItsRevisionBoundFails(t *testing.T) {
@@ -534,3 +663,65 @@ func digestOf(unreadable bool) string {
} }
return mdigest('a') return mdigest('a')
} }
// H-A-508 (review rounds 1, 2): a newer entry of the branch heard while the step's build runs withdraws that build (the key
// ends "withdrawn: … superseded by …", as main.327's mesh-delivery-gate build did); the step waiting on it ends superseded,
// naming the newer fingerprint, judged before the build's failed end, never failed.
func aNewerEntryWhileTheBuildRunsSupersedesTheStep(t *testing.T) {
r := newRig(t, goBundle)
var asked int32
running := make(chan struct{})
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
if atomic.AddInt32(&asked, 1) == 1 { // fp1's ask runs until it is withdrawn
defer close(running)
return buildstep.Step{ID: a.ID, Node: "ace", State: buildstep.StepRunning, Started: time.Now()}
}
return r.answer(a)
}
r.b.Asks = buildrun.Asker{Seats: testSeats(), Publisher: r.asks, Waiter: r.asks, Bound: 2 * time.Second, Dropper: &seatDrops{}}
r.b.StepEntry = func(context.Context, string) (meshcatalog.CatalogEntry, error) {
return meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1, ManifestDigest: mdigest('a'), Path: "modules/m"}, nil
}
r.b.Module(t.Context(), "m", moduleValue(t, "modules/m")) // fp1, the newest entry heard, is built
<-running
ended := make(chan meshbuilds.StepEnded, 1)
go func() {
ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.1.m", Step: meshbuilds.StepRunStepBuild, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
}()
// The step waits on the end of fp1's build in flight before the newer entry is heard.
for deadline := time.Now().Add(5 * time.Second); ; runtime.Gosched() {
r.b.mu.Lock()
n := len(r.b.stepWaits[r.key])
r.b.mu.Unlock()
if n > 0 {
break
}
select {
case end := <-ended:
t.Fatalf("the step ended before it waited on the build in flight: %+v", end)
default:
}
if time.Now().After(deadline) {
t.Fatal("the step never waited on the build in flight")
}
}
newer, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp: "src1:" + hex64('f'), Fp2: fp2, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)})
if err != nil {
t.Fatal(err)
}
r.b.Module(t.Context(), "m", newer)
var end meshbuilds.StepEnded
select {
case end = <-ended:
case <-time.After(5 * time.Second):
t.Fatal("the step never ended")
}
r.b.Wait()
if v := valueOf(t, r.st, r.key); v.State != builds.BuildFailed || !strings.HasPrefix(v.Error, withdrawnPrefix) || !strings.Contains(v.Error, "superseded by the fingerprint "+fp2) {
t.Fatalf("fp1's key = %+v, want its build withdrawn, superseded by %s", v, fp2)
}
if end.Outcome != meshbuilds.StepEndedOutcomeSuperseded || !strings.Contains(end.Said, "m at "+fp1+" is superseded by "+fp2) {
t.Errorf("end = %+v, want superseded by %s", end, fp2)
}
}
@@ -56,7 +56,7 @@ type ReAsk struct {
Failed string `json:"failed,omitempty"` Failed string `json:"failed,omitempty"`
Revision uint64 `json:"revision,omitempty"` Revision uint64 `json:"revision,omitempty"`
Asks map[string]string `json:"asks,omitempty"` Asks map[string]string `json:"asks,omitempty"`
// Name is the numbered name (`<module>/<artifact>`) of a ModeFloorAgain value; Version is a ModeRepublish value's // Name is the module or node a hand act names; Version is a ModeRepublish value's
// request and Queued the builder's answer to it: the versions it queued, `<module> <version>`. // request and Queued the builder's answer to it: the versions it queued, `<module> <version>`.
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"` Version string `json:"version,omitempty"`
@@ -74,14 +74,11 @@ const ModePublish = "publish"
// optional, name what to publish again; the builder answers with the versions it queued (Queued). // optional, name what to publish again; the builder answers with the versions it queued (Queued).
const ModeRepublish = "republish" const ModeRepublish = "republish"
// ModePublishDrop and ModePublishFirst are the Modes of a reasks value of builder_publish_drop and builder_publish_first (design // ModePublishDrop is the Mode of a reasks value of builder_publish_drop (design 47 H2 §793): Module and Version name the item;
// 47 H2 §793): Module and Version name the item; the builder terminates it, or puts it again as live and terminates the old. // the builder terminates it.
const ( const ModePublishDrop = "publish-drop"
ModePublishDrop = "publish-drop"
ModePublishFirst = "publish-first"
)
// NewPublishAct is the value builder_publish_drop (mode ModePublishDrop) or builder_publish_first (ModePublishFirst) writes // NewPublishAct is the value builder_publish_drop (mode ModePublishDrop) writes
// (§793): its key, `<mode>.<unix nanoseconds>` (a call is one value), and the value. Module, version and why are required. // (§793): its key, `<mode>.<unix nanoseconds>` (a call is one value), and the value. Module, version and why are required.
func NewPublishAct(mode, module, version, why, by string, at time.Time) (string, []byte, error) { func NewPublishAct(mode, module, version, why, by string, at time.Time) (string, []byte, error) {
module, version = strings.TrimSpace(module), strings.TrimSpace(version) module, version = strings.TrimSpace(module), strings.TrimSpace(version)
@@ -95,9 +92,6 @@ func NewPublishAct(mode, module, version, why, by string, at time.Time) (string,
return mode + "." + strconv.FormatInt(at.UnixNano(), 10), data, err return mode + "." + strconv.FormatInt(at.UnixNano(), 10), data, err
} }
// ModeFloorAgain is the Mode of a reasks value of builder_floor_again (design 51 *The floor*).
const ModeFloorAgain = "floor-again"
// NewRepublish is the value builder_publish_again writes (design 47 G §588): its key, `republish.<unix nanoseconds>` // NewRepublish is the value builder_publish_again writes (design 47 G §588): its key, `republish.<unix nanoseconds>`
// (a call is one value, never a build key), and the value. Module and version are each optional. // (a call is one value, never a build key), and the value. Module and version are each optional.
func NewRepublish(module, version, why, by string, at time.Time) (string, []byte, error) { func NewRepublish(module, version, why, by string, at time.Time) (string, []byte, error) {
@@ -112,20 +106,6 @@ func NewRepublish(module, version, why, by string, at time.Time) (string, []byte
return "republish." + strconv.FormatInt(at.UnixNano(), 10), data, err return "republish." + strconv.FormatInt(at.UnixNano(), 10), data, err
} }
// NewFloorAgain is the value builder_floor_again writes for a name: the key `floor.<name escaped>`, never a build key,
// and the value.
func NewFloorAgain(name, why, by string, at time.Time) (string, []byte, error) {
name = strings.TrimSpace(name)
if module, artifact, ok := strings.Cut(name, "/"); !ok || module == "" || artifact == "" {
return "", nil, fmt.Errorf("name %q is not a numbered name, <module>/<artifact>, as builder_versions lists it", name)
}
if strings.TrimSpace(why) == "" {
return "", nil, errors.New("say why the floor is asked again (why)")
}
data, err := json.Marshal(ReAsk{V: 1, Why: strings.TrimSpace(why), By: by, At: at.UTC(), Mode: ModeFloorAgain, Name: name})
return "floor." + versions.EscapeToken(name), data, err
}
// ModeOldFormDrop is the Mode of a reasks value of builder_old_form's drop (design 51 *Every build keeps the old // ModeOldFormDrop is the Mode of a reasks value of builder_old_form's drop (design 51 *Every build keeps the old
// reference form*): a retired node dropped from the count by hand; Name is the node. // reference form*): a retired node dropped from the count by hand; Name is the node.
const ModeOldFormDrop = "old-form-drop" const ModeOldFormDrop = "old-form-drop"
@@ -2,22 +2,11 @@ package versions
import ( import (
"context" "context"
"fmt"
"time" "time"
) )
// The tools' descriptions.
const (
FloorAgainDescription = "Refused for every name: the builder numbers nothing of its own and asks no floor (design 47 H H-A-159); " +
"a version is numbered by the reservation (design 47 G §369, builder_reserved). Kept until design 47 G §372 removes it with " +
"the state versions."
)
// Acts are the builder's hand acts on its versions, answered by its program (the tools bundle writes them to reasks). // Acts are the builder's hand acts on its versions, answered by its program (the tools bundle writes them to reasks).
type Acts struct { type Acts struct {
Numberer *Numberer
// Reconsider looks at every module again, so a claim asks a name's floor.
Reconsider func(ctx context.Context)
// Republish queues the reserved versions builder_publish_again names (design 47 G §588): the versions it queued. // Republish queues the reserved versions builder_publish_again names (design 47 G §588): the versions it queued.
Republish func(ctx context.Context, module, version string) ([]string, error) Republish func(ctx context.Context, module, version string) ([]string, error)
// DropOldForm drops a retired node from the old form's count by hand (builder_old_form): its answer, or why not. // DropOldForm drops a retired node from the old form's count by hand (builder_old_form): its answer, or why not.
@@ -27,15 +16,6 @@ type Acts struct {
ReserveDone func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) ReserveDone func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error)
// DropReserved drops a module's reservation of one MAJOR.MINOR by hand (builder_reserved_drop): its answer, or why not. // DropReserved drops a module's reservation of one MAJOR.MINOR by hand (builder_reserved_drop): its answer, or why not.
DropReserved func(ctx context.Context, module, series, by, why string, at time.Time) (string, error) DropReserved func(ctx context.Context, module, series, by, why string, at time.Time) (string, error)
// PublishDrop terminates one publish item, and PublishFirst puts it again as live and terminates the old (builder_publish_drop, // PublishDrop terminates one publish item (builder_publish_drop, design 47 H2 §793): the answer, or why not.
// builder_publish_first, design 47 H2 §793): the answer, or why not. PublishDrop func(ctx context.Context, module, version, by, why string) (string, error)
PublishDrop func(ctx context.Context, module, version, by, why string) (string, error)
PublishFirst func(ctx context.Context, module, version, by, why string) (string, error)
}
// FloorAgain is builder_floor_again of name: refused, since the builder numbers nothing of its own and no claim asks a floor
// (design 47 H H-A-159; the reservation numbers, G §369). The tool stays until G §372 removes it with the state versions.
func (a Acts) FloorAgain(_ context.Context, name string) (string, error) {
return "", fmt.Errorf("the floor of %s is not asked: the builder numbers nothing of its own and asks no floor (design 47 H H-A-159); "+
"a version is numbered by the reservation (G §369, builder_reserved)", name)
} }
@@ -2,10 +2,7 @@ package versions
import ( import (
"context" "context"
"fmt"
"sort"
"strings" "strings"
"time"
) )
// The registry seats a version is published to (design 51 *The seats*), by what is published. // The registry seats a version is published to (design 51 *The seats*), by what is published.
@@ -54,207 +51,3 @@ func TagPrefix(path string) string {
} }
return path + "/v" return path + "/v"
} }
// ClaimArtifact is one artifact of a trunk build to number.
type ClaimArtifact struct {
Artifact, Kind, Language string
}
// BuildClaim is a trunk build at its claim: what Numberer.Number numbers.
type BuildClaim struct {
Module, Path, Repository, Fingerprint, Commit, Series string
// Revision is the source revision of the merge (a package is numbered per revision); Merge its sequence, for order.
Revision string
Merge uint64
Artifacts []ClaimArtifact
// Done are the digests of the build's done key, by artifact, when the claim is a look at a build already done: what it
// left unnumbered (a package whose name was not known yet, a floor that was silent) is numbered with them, so
// version.numbered carries the digest its build module publishes late. Nil for a build still to make.
Done map[string]string
}
// Numbering is what the claim got.
type Numbering struct {
// Versions are each artifact's version, by artifact; an artifact built unnumbered (its floor not known) has none.
Versions map[string]string
// Unnumbered are the artifacts built and published by digest, numbered once their floor answers (ADR 0617 §1).
Unnumbered []string
// Wait is why the build waits: a package whose floor is not known (design 51 *The floor*). Nothing is claimed.
Wait string
// Said are the builder's narrations of each decision, for its process log and its build log (build.said).
Said []Narration
// Names are the names each numbered artifact was numbered under, by artifact (NameOf, or a package's name in its
// ecosystem).
Names map[string]string
// Refused is why the build is refused: a package's published versions could not be read (ADR 0666 §15). Nothing else
// is numbered.
Refused string
}
// NameOf is the name artifact of module was numbered under in this numbering.
func (g Numbering) NameOf(module, artifact string) string {
if name := g.Names[artifact]; name != "" {
return name
}
return NameOf(module, artifact)
}
// Narration is one line the builder says in its build log (design 51: the build log says a version was kept, and
// why), and what it narrates.
type Narration struct{ Line, Why string }
// What a narration of the build log narrates (the build.said entry's why).
const (
SaidNumbered = "numbered"
SaidKept = "kept"
SaidWaiting = "waiting"
SaidUnnumbered = "unnumbered"
SaidOldFormClosed = "old-form-closed"
)
// narrationOf is a decision's narration.
func narrationOf(name string, d Decision) Narration {
why := SaidNumbered
switch {
case d.Keep:
why = SaidKept
case d.Wait:
why = SaidWaiting
case d.Unnumbered:
why = SaidUnnumbered
}
return Narration{Line: name + ": " + d.Why, Why: why}
}
// Numberer numbers trunk builds at their claim (design 51 *The versions*, DLV-B2, B3): it asks a name's floor only
// when versions holds nothing for it, and records a silent floor as a wait (FloorWaits, woken by its source's event).
type Numberer struct {
Versions Versions
Floor FloorSources
Waits *FloorWaits
// Holder is the module holding a seat, whose health condition's clear wakes a silent seat source; nil names none.
Holder func(seat string) string
// Names answers a package's name in its ecosystem; nil numbers a package as NameOf names it.
Names PackageNames
// Publishing is told each version Built recorded that is still numbered, its holder's word not heard yet: the
// builder arms its publish bound (publish.go); nil arms none.
Publishing func(ctx context.Context, e Entry)
Now func() time.Time
}
// Number numbers every numbered artifact of c. An error is a store that cannot be read or written: the claim is then
// built as before, unnumbered, and said.
func (n *Numberer) Number(ctx context.Context, c BuildClaim) (Numbering, error) {
out := Numbering{Versions: map[string]string{}, Names: map[string]string{}}
arts := append([]ClaimArtifact(nil), c.Artifacts...)
sort.Slice(arts, func(i, j int) bool { return arts[i].Artifact < arts[j].Artifact })
for _, a := range arts {
seat, kind, ok := SeatOf(a.Kind, a.Language)
if !ok {
continue
}
name := NameOf(c.Module, a.Artifact)
if kind == KindPackage && n.Names != nil {
// A package is numbered, asked for its floor and published under its name in its ecosystem (design 32), the
// name the holder's builder_versions question and the seat's versions name it by.
named, known, err := n.Names(ctx, c.Module, a.Artifact)
if err != nil || !known {
why := "the indexer's packages state names no name of it in its ecosystem yet (it writes one at the module's next trunk merge)"
if err != nil {
why = "the indexer's packages state cannot be read: " + err.Error()
}
out.Unnumbered = append(out.Unnumbered, a.Artifact)
out.Said = append(out.Said, Narration{Line: name + ": built unnumbered: " + why, Why: SaidUnnumbered})
continue
}
name = named
}
out.Names[a.Artifact] = name
entries, err := n.Versions.Of(ctx, name)
if err != nil && kind == KindPackage {
// A build that cannot read the published packages refuses, naming the unread state, never building against a
// guess (ADR 0666 §15; design 51 *The versions*, line 287).
out.Refused = fmt.Sprintf("%s: refused: the builder's state %s cannot be read, so its published versions are not known: %v", name, State, err)
return out, nil
}
if err != nil {
return out, err
}
var floor Floor
var why map[string]string
if len(entries) == 0 {
floor, why = n.askFloor(ctx, seat, name, c)
}
d, _, err := n.Versions.Number(ctx, Claim{Name: name, Kind: kind, Series: c.Series, Module: c.Module, Fingerprint: c.Fingerprint,
Commit: c.Commit, Revision: c.Revision, Digest: c.Done[a.Artifact], Seat: seat, Merge: c.Merge, Floor: floor})
if err != nil {
return out, err
}
out.Said = append(out.Said, narrationOf(name, d))
switch {
case d.Wait:
n.wait(name, seat, floor, why)
out.Wait = name + ": " + d.Why
return out, nil
case d.Unnumbered:
n.wait(name, seat, floor, why)
out.Unnumbered = append(out.Unnumbered, a.Artifact)
continue
}
if n.Waits != nil {
n.Waits.Answered(name)
}
out.Versions[a.Artifact] = d.Version
}
return out, nil
}
func (n *Numberer) askFloor(ctx context.Context, seat, name string, c BuildClaim) (Floor, map[string]string) {
return n.Floor.Ask(ctx, FloorOf{Seat: seat, Name: name, Repository: c.Repository, Prefix: TagPrefix(c.Path)})
}
func (n *Numberer) wait(name, seat string, f Floor, why map[string]string) {
if n.Waits == nil {
return
}
holder := ""
if n.Holder != nil {
holder = n.Holder(seat)
}
now := time.Now()
if n.Now != nil {
now = n.Now()
}
n.Waits.Wait(name, seat, holder, f, why, now)
}
// Built records the digest each numbered artifact was built with, on an entry that holds none yet or was never published: what the holder's
// builder_versions question compares (ADR 0605 §4).
func (n *Numberer) Built(ctx context.Context, c BuildClaim, got Numbering, digests map[string]string) error {
var errs []string
for artifact, version := range got.Versions {
d := digests[artifact]
if d == "" {
continue
}
e, err := n.Versions.Mark(ctx, got.NameOf(c.Module, artifact), version, func(e *Entry) {
// The new digest replaces the recorded one only while no published was said for the number (design 51
// *Tools of the builder*): a rebuild of a gone file under the same number.
if e.Digest == "" || e.State == Numbered || e.State == Refused {
e.Digest = d
}
})
if err != nil {
errs = append(errs, err.Error())
continue
}
if e.State == Numbered && n.Publishing != nil {
n.Publishing(ctx, e)
}
}
if len(errs) > 0 {
sort.Strings(errs)
return fmt.Errorf("the built digests could not be recorded: %s", strings.Join(errs, "; "))
}
return nil
}
@@ -122,20 +122,3 @@ func EntriesOf(branches *meshcatalogclient.Branches) Entries {
func HolderOf(branches *meshcatalogclient.Branches) func(seat string) (string, bool) { func HolderOf(branches *meshcatalogclient.Branches) func(seat string) (string, bool) {
return branches.Claimant return branches.Claimant
} }
// RequirementsFrom answers the versions of a package the entries of every followed half require, each once, in order: what a
// consumer's entry names for it in its packages (design 47 G A-119), the floor's third source.
func RequirementsFrom(all Entries) func(ctx context.Context, name string) ([]string, error) {
return func(_ context.Context, name string) ([]string, error) {
seen := map[string]bool{}
var out []string
for _, e := range all() {
if v := e.Packages[name]; v != "" && !seen[v] {
seen[v] = true
out = append(out, v)
}
}
sort.Strings(out)
return out, nil
}
}
@@ -66,22 +66,3 @@ func TestPackageNamesAreReadFromTheCatalogHalfsEntries(t *testing.T) {
t.Errorf("CarriersFrom(twin) = %v, want %v", got, want) t.Errorf("CarriersFrom(twin) = %v, want %v", got, want)
} }
} }
// Design 47 G A-119: the floor's requirements are what the catalog half's entries name for the package, each version once.
func TestRequirementsFromAreTheVersionsEntriesNameForAPackage(t *testing.T) {
entries := func() []meshcatalog.CatalogEntry {
return []meshcatalog.CatalogEntry{
{Module: "a", Packages: map[string]string{"x/sdk": "v0.0.0-2026-aaa", "y": "v1.0.0"}},
{Module: "b", Packages: map[string]string{"x/sdk": "v0.0.0-2026-bbb"}},
{Module: "c", Packages: map[string]string{"x/sdk": "v0.0.0-2026-aaa"}},
{Module: "d"},
}
}
got, err := RequirementsFrom(entries)(context.Background(), "x/sdk")
if err != nil || !reflect.DeepEqual(got, []string{"v0.0.0-2026-aaa", "v0.0.0-2026-bbb"}) {
t.Errorf("requirements = %v, %v", got, err)
}
if got, _ := RequirementsFrom(entries)(context.Background(), "none"); len(got) != 0 {
t.Errorf("a package no entry names has requirements %v", got)
}
}
@@ -1,332 +0,0 @@
package versions
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
)
// FloorSources are the three sources of a name's floor (design 51 *The floor*): each a tool call that answers the
// versions it knows of a name, or an error when it does not answer.
type FloorSources struct {
// Seat is `seat:<registry>.versions` of the registry seat the name is published to.
Seat func(ctx context.Context, seat, name string) ([]string, error)
// Tags is the seat git's tags: the git tags of the repository the name is built from, under prefix.
Tags func(ctx context.Context, repository, prefix string) ([]string, error)
// Requirements are the versions of a package the catalog half's entries require (design 47 G A-119).
Requirements func(ctx context.Context, name string) ([]string, error)
}
// FloorOf names what a floor is asked for: the name on its seat, and the repository and tag prefix of its git tags.
type FloorOf struct{ Seat, Name, Repository, Prefix string }
// Ask asks the three sources of a name; a source that errs, or is not wired, is named in Silent with its error in why.
func (s FloorSources) Ask(ctx context.Context, of FloorOf) (Floor, map[string]string) {
seat, name := of.Seat, of.Name
var f Floor
why := map[string]string{}
ask := func(source string, call func() ([]string, error), into *[]string) {
if call == nil {
f.Silent, why[source] = append(f.Silent, source), "not asked: the builder has no path to it"
return
}
got, err := call()
if err != nil {
f.Silent, why[source] = append(f.Silent, source), err.Error()
return
}
*into = got
}
var seatCall, tagsCall, reqCall func() ([]string, error)
if s.Seat != nil {
seatCall = func() ([]string, error) { return s.Seat(ctx, seat, name) }
}
if s.Tags != nil {
tagsCall = func() ([]string, error) { return s.Tags(ctx, of.Repository, of.Prefix) }
}
if s.Requirements != nil {
reqCall = func() ([]string, error) { return s.Requirements(ctx, name) }
}
ask(SourceSeat, seatCall, &f.Seat)
ask(SourceTags, tagsCall, &f.Tags)
ask(SourceRequirements, reqCall, &f.Requirements)
return f, why
}
// What wakes a name waiting on its floor, never a timer (design 51, DLV-B3b): the source that was silent saying
// something, or its module's health condition clearing.
const (
// WakePublished is the holder's `published` on the builder's durable consumer of `<seat>.events`.
WakePublished = "published"
// WakeRevision is a catalog revision the builder hears (the catalog half's entry changed): tags and requirements are asked again.
WakeRevision = "catalog-revision"
// WakeTakenIn is the indexer's next `take-in.taken`, in place of the retired manifest-accepted: the floor looks at every
// module again (design 47 H H-A-116).
WakeTakenIn = "take-in.taken"
// WakeCleared is the condition keeper's clear of a silent module's health condition on `mesh-conditions`.
WakeCleared = "condition-cleared"
// WakeByHand is builder_floor_again, a hand act.
WakeByHand = "by hand"
)
// sourceOfWake is the floor source each event says something of; a clear names the source by its module.
var sourceOfWake = map[string]string{WakePublished: SourceSeat, WakeTakenIn: SourceRequirements}
// SourceSeats are the seats whose holders are the floor's tag and requirement sources (design 47 G A-82): the seat git (tags)
// and the seat mesh-catalog (requirements), the holders read from the seat list and the catalog half.
var SourceSeats = map[string]string{SourceTags: "git", SourceRequirements: "mesh-catalog"}
// FloorWait is one name waiting on its floor: the sources still silent and why, since when; the finding the builder
// writes names them, cleared once all three answer.
type FloorWait struct {
Name string `json:"name"`
Seat string `json:"seat"`
Silent []string `json:"silent"`
Why map[string]string `json:"why,omitempty"`
Since time.Time `json:"since"`
// Holder is the module holding the name's seat: its condition's clear wakes the seat source.
Holder string `json:"holder,omitempty"`
}
// Finding is the floor finding's words.
func (w FloorWait) Finding() string {
var parts []string
for _, s := range w.Silent {
p := s
if why := w.Why[s]; why != "" {
p += " (" + why + ")"
}
parts = append(parts, p)
}
return fmt.Sprintf("the floor of %s is not known since %s: %s did not answer; nothing of it is numbered until all three answer",
w.Name, w.Since.UTC().Format(time.RFC3339), strings.Join(parts, ", "))
}
// The builder's state floor-waits (DLV-B4): each name waiting on its floor, keyed by its escaped name, so a restarted
// builder still knows which names its silent sources' events wake; builder_floor_waits reads it.
const (
FloorWaitsState = "floor-waits"
FloorWaitsTool = "builder_floor_waits"
)
// FloorWaitKey is a wait's key in floor-waits.
func FloorWaitKey(name string) string { return EscapeToken(name) }
// FloorKeeper keeps the waits on the bus: Put a wait's value, Delete its key.
type FloorKeeper interface {
Put(key string, value []byte) error
Delete(key string) error
}
// FloorWaits are the names waiting on their floor. Wake answers which names to ask again for an event, Answered drops
// a name once all three answered; the builder's finding for each is the wait's Finding. Once Kept, every change is
// written to the state floor-waits as well.
type FloorWaits struct {
mu sync.Mutex
waits map[string]FloorWait
keeper FloorKeeper
// Logf says a wait that could not be kept; nil says nothing.
Logf func(string, ...any)
// Holder finds the module holding a seat (the catalog half's claim); a source's module is the holder of its SourceSeats seat.
Holder func(seat string) (string, bool)
// Said is told each wait recorded (raised) and each answered (not raised): the builder's finding floor-silent.
Said func(w FloorWait, raised bool)
}
// FloorSilent is the kind of the floor finding.
const FloorSilent = "floor-silent"
// Keep binds the state: the waits it holds that are not known here are taken in (a restarted builder's), every wait
// known here is written to it, and every change from now on is.
func (fw *FloorWaits) Keep(k FloorKeeper, held []FloorWait) {
fw.mu.Lock()
if fw.waits == nil {
fw.waits = map[string]FloorWait{}
}
for _, w := range held {
if _, had := fw.waits[w.Name]; !had && w.Name != "" {
fw.waits[w.Name] = w
}
}
fw.keeper = k
all := make([]FloorWait, 0, len(fw.waits))
for _, w := range fw.waits {
all = append(all, w)
}
fw.mu.Unlock()
for _, w := range all {
fw.put(k, w)
}
}
func (fw *FloorWaits) put(k FloorKeeper, w FloorWait) {
if k == nil {
return
}
data, err := json.Marshal(w)
if err == nil {
err = k.Put(FloorWaitKey(w.Name), data)
}
if err != nil && fw.Logf != nil {
fw.Logf("the floor wait of %s is not kept in %s (a restart forgets it until its next claim): %v", w.Name, FloorWaitsState, err)
}
}
// DecodeFloorWait reads one value of floor-waits.
func DecodeFloorWait(raw []byte) (FloorWait, error) {
var w FloorWait
if err := json.Unmarshal(raw, &w); err != nil {
return FloorWait{}, err
}
if w.Name == "" {
return FloorWait{}, errors.New("a floor wait names no name")
}
return w, nil
}
// Wait records that name's floor is not known.
func (fw *FloorWaits) Wait(name, seat, holder string, f Floor, why map[string]string, now time.Time) FloorWait {
fw.mu.Lock()
if fw.waits == nil {
fw.waits = map[string]FloorWait{}
}
w, had := fw.waits[name]
if !had {
w.Since = now
}
w.Name, w.Seat, w.Holder, w.Silent, w.Why = name, seat, holder, slices.Clone(f.Silent), why
fw.waits[name] = w
k := fw.keeper
fw.mu.Unlock()
fw.put(k, w)
if fw.Said != nil {
fw.Said(w, true)
}
return w
}
// Answered drops name: its floor is known. It says whether the name waited, so its finding is cleared.
func (fw *FloorWaits) Answered(name string) bool {
fw.mu.Lock()
w, had := fw.waits[name]
delete(fw.waits, name)
k := fw.keeper
fw.mu.Unlock()
if had && fw.Said != nil {
fw.Said(w, false)
}
if had && k != nil {
if err := k.Delete(FloorWaitKey(name)); err != nil && fw.Logf != nil {
fw.Logf("the floor wait of %s is not cleared from %s: %v", name, FloorWaitsState, err)
}
}
return had
}
// FloorWaitsAnswer is what builder_floor_waits answers: every name waiting on its floor, oldest first, with its finding.
type FloorWaitsAnswer struct {
Waits []FloorWaitRead `json:"waits"`
}
// FloorWaitRead is one wait as builder_floor_waits shows it.
type FloorWaitRead struct {
FloorWait
Finding string `json:"finding"`
}
// AnswerFloorWaits is builder_floor_waits, read from the state floor-waits.
func AnswerFloorWaits(r Reader) (FloorWaitsAnswer, error) {
keys, err := r.Keys()
if err != nil {
return FloorWaitsAnswer{}, err
}
out := FloorWaitsAnswer{Waits: []FloorWaitRead{}}
for _, k := range keys {
raw, ok, err := r.Get(k)
if err != nil {
return FloorWaitsAnswer{}, err
}
if !ok {
continue
}
w, err := DecodeFloorWait(raw)
if err != nil {
return FloorWaitsAnswer{}, fmt.Errorf("%s.%s: %w", FloorWaitsState, k, err)
}
out.Waits = append(out.Waits, FloorWaitRead{FloorWait: w, Finding: w.Finding()})
}
sort.Slice(out.Waits, func(i, j int) bool {
if !out.Waits[i].Since.Equal(out.Waits[j].Since) {
return out.Waits[i].Since.Before(out.Waits[j].Since)
}
return out.Waits[i].Name < out.Waits[j].Name
})
return out, nil
}
// FloorWaitsDescription is builder_floor_waits' description.
const FloorWaitsDescription = "The names waiting on their floor (the builder's state floor-waits, design 51 *The floor*), oldest first: " +
"each name, its registry seat, the sources still silent and why, since when, and the finding the builder says for it. " +
"Nothing of a waiting name is numbered until all three sources answer; builder_floor_again asks one again by hand. Read-only."
// Wake answers the names to ask their floor again on an event: kind one of the Wake constants; seat the seat a
// `published` came on; module the module whose condition cleared. A name is woken only when the event says something
// of a source it waits on; WakeByHand with a name wakes that name alone.
func (fw *FloorWaits) Wake(kind, seat, module, name string) []string {
fw.mu.Lock()
defer fw.mu.Unlock()
var out []string
for n, w := range fw.waits {
switch kind {
case WakeByHand:
if n == name {
out = append(out, n)
}
case WakeCleared:
for _, s := range w.Silent {
if fw.holds(SourceSeats[s], module) || (s == SourceSeat && w.Holder != "" && w.Holder == module) {
out = append(out, n)
break
}
}
default:
src := sourceOfWake[kind]
if kind == WakeRevision {
if slices.Contains(w.Silent, SourceTags) || slices.Contains(w.Silent, SourceRequirements) {
out = append(out, n)
}
} else if slices.Contains(w.Silent, src) && (kind != WakePublished || seat == "" || seat == w.Seat) {
out = append(out, n)
}
}
}
sort.Strings(out)
return out
}
// Waiting is every wait, by name.
func (fw *FloorWaits) Waiting() []FloorWait {
fw.mu.Lock()
defer fw.mu.Unlock()
out := make([]FloorWait, 0, len(fw.waits))
for _, w := range fw.waits {
out = append(out, w)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// holds is whether module holds seat on the catalog half.
func (fw *FloorWaits) holds(seat, module string) bool {
if seat == "" || module == "" || fw.Holder == nil {
return false
}
holder, ok := fw.Holder(seat)
return ok && holder == module
}
@@ -1,10 +1,5 @@
package versions package versions
import (
"context"
"fmt"
)
// The registry seats' events the builder hears on its durable consumer of each `<seat>.events` (design 51 *How a // The registry seats' events the builder hears on its durable consumer of each `<seat>.events` (design 51 *How a
// publish ends*, DLV-B4). // publish ends*, DLV-B4).
const ( const (
@@ -26,56 +21,3 @@ type Outcome struct {
// Tags are, on kept, the other tags still naming its digest. // Tags are, on kept, the other tags still naming its digest.
Tags []string `json:"tags,omitempty"` Tags []string `json:"tags,omitempty"`
} }
// Heard takes one seat event in: a numbered version's entry turns published (with its digest when it held none),
// refused with the holder's reason, removed with its reason and the event's id, or kept (another tag names its digest)
// with the other tags; a by-digest publish (no version)
// marks nothing. It answers the names waiting on their floor that the event wakes: a `published` says the seat
// answers (design 51 *The floor*).
func (n *Numberer) Heard(ctx context.Context, seat, event, id string, o Outcome) ([]string, error) {
var wake []string
if event == HeardPublished && n.Waits != nil {
wake = n.Waits.Wake(WakePublished, seat, "", "")
}
if o.Version == "" {
return wake, nil
}
var change func(*Entry)
switch event {
case HeardPublished:
// A published of other bytes than an entry records under its number is no publish of that entry: the reservation
// numbered it and takes it in (design 47 H H-A-159, G §369, A-415; ADR 0605 §4), and the entry stays as it is.
if e, ok, _, err := n.Versions.Recorded(ctx, o.Name, o.Version, o.Digest); err == nil && !ok && e.Digest != "" && o.Digest != "" && e.Digest != o.Digest {
return wake, fmt.Errorf("%s@%s is recorded with digest %s, so %s's published of %s is %w", o.Name, o.Version, e.Digest, seat, o.Digest, ErrNotNumbered)
}
change = func(e *Entry) {
e.State, e.Reason = Published, ""
if e.Digest == "" {
e.Digest = o.Digest
}
}
case HeardRefused:
change = func(e *Entry) {
if e.State != Published {
e.State, e.Reason, e.RefusedDigest = Refused, o.Reason, o.Digest
}
}
case HeardRemoved:
change = func(e *Entry) { e.State, e.Reason, e.RemovedBy = Removed, o.Reason, id }
case HeardKept:
change = func(e *Entry) {
if e.State != Removed {
e.State, e.Reason, e.KeptWith = Kept, o.Reason, append([]string(nil), o.Tags...)
if e.Reason == "" {
e.Reason = "shared-digest"
}
}
}
default:
return wake, fmt.Errorf("%s says %q, which the builder does not hear", seat, event)
}
if _, err := n.Versions.Mark(ctx, o.Name, o.Version, change); err != nil {
return wake, fmt.Errorf("%s's %s of %s@%s: %w", seat, event, o.Name, o.Version, err)
}
return wake, nil
}
@@ -52,7 +52,7 @@ func TestTheIndexFindsAPublishedReservationInOneRead(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if i%2 == 0 { // half are built, each with its own digest if i%2 == 0 { // half are built, each with its own digest
if _, err := r.Built(ctx, m, "0.1.0", m+":a", "sha256:"+m, nil); err != nil { if _, _, err := r.Built(ctx, m, "0.1.0", map[string]string{m + ":a": "sha256:" + m}, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@@ -70,7 +70,7 @@ func TestTheIndexFindsAPublishedReservationInOneRead(t *testing.T) {
if _, err := r.Reserve(ctx, m, "0.1", []string{m + ":a"}, Source{Fingerprint: "fp" + m}); err != nil { if _, err := r.Reserve(ctx, m, "0.1", []string{m + ":a"}, Source{Fingerprint: "fp" + m}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := r.Built(ctx, m, "0.1.0", m+":a", "sha256:"+m, nil); err != nil { if _, _, err := r.Built(ctx, m, "0.1.0", map[string]string{m + ":a": "sha256:" + m}, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@@ -4,121 +4,15 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"sort"
"strings" "strings"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
) )
// PackagesState is the indexer's packages state as the builder reads it (its manifest's reads grant): its keys, and one
// key's value (found false when it holds none).
type PackagesState interface {
Keys(ctx context.Context) ([]string, error)
Get(ctx context.Context, key string) (value []byte, found bool, err error)
}
// NamesIn are a package's names in its ecosystem as the indexer's packages state holds them (design 32): the name of the
// series key that names module and artifact as what it is built from. A series key is named `<name>.<series>`; a key
// with no dot is a mesh Go module's published packages, not a series. A value that does not decode is passed over.
func NamesIn(s PackagesState) PackageNames {
return func(ctx context.Context, module, artifact string) (string, bool, error) {
keys, err := s.Keys(ctx)
if err != nil {
return "", false, err
}
sort.Strings(keys)
built := NameOf(module, artifact)
for _, key := range keys {
if !isSeriesKey(key) {
continue
}
value, found, err := s.Get(ctx, key)
if err != nil {
return "", false, err
}
if !found {
continue
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value) // the indexer's value of a series key (mesh-sdk's contract, J4)
if err != nil || v.Package != built {
continue
}
return v.Name, true, nil
}
return "", false, nil
}
}
// NamedModule is the module a value of the indexer's packages state names a package's name for (design 32), and that
// name: a series key whose value names a name and the <module>/<artifact> it is built from. The builder looks at that module again when
// the value is heard, so a done build that left the package unnumbered (its name not known at its claim) is numbered then.
func NamedModule(key string, value []byte) (module, name string, ok bool) {
if !isSeriesKey(key) {
return "", "", false
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value)
if err != nil || v.Name == "" {
return "", "", false
}
module, artifact, cut := strings.Cut(v.Package, "/")
if !cut || module == "" || artifact == "" {
return "", "", false
}
return module, v.Name, true
}
// isSeriesKey says whether a key of the indexer's packages state is a series key (`<package>.<series>`), not a per-module one.
func isSeriesKey(key string) bool {
_, _, ok := meshcatalog.ParsePackagesByPackageSeriesKey(key)
return ok
}
// Built is a module's artifact, which a package's name is the name of. // Built is a module's artifact, which a package's name is the name of.
type Built struct{ Module, Artifact string } type Built struct{ Module, Artifact string }
// Carriers are the module artifacts a package's name in its ecosystem is the name of, as the catalog half's packages view // moduleOfCarriers is the module and artifact a package's name is built from, found false for a name no entry carries; more
// holds them (the inverse of NamesIn; design 47 G §572, §478): each distinct module and artifact of a series key whose value // than one entry carrying it is an error naming them. The carriers are read from the catalog half's entries (CarriersFrom,
// names that name, sorted. A name no entry carries answers none. // design 47 G §348), never from the indexer's state.
func Carriers(s PackagesState) func(ctx context.Context, name string) ([]Built, error) {
return func(ctx context.Context, name string) ([]Built, error) {
keys, err := s.Keys(ctx)
if err != nil {
return nil, err
}
sort.Strings(keys)
seen := map[Built]bool{}
var out []Built
for _, key := range keys {
if !isSeriesKey(key) {
continue
}
value, found, err := s.Get(ctx, key)
if err != nil {
return nil, err
}
if !found {
continue
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value)
if err != nil || v.Name != name {
continue
}
if module, artifact, cut := strings.Cut(v.Package, "/"); cut && module != "" && artifact != "" && !seen[Built{module, artifact}] {
seen[Built{module, artifact}] = true
out = append(out, Built{module, artifact})
}
}
return out, nil
}
}
// ModuleOf is the module and artifact a package's name is built from (Carriers), found false for a name no entry carries; more
// than one entry carrying it is an error naming them.
func ModuleOf(s PackagesState) func(ctx context.Context, name string) (module, artifact string, found bool, err error) {
return moduleOfCarriers(Carriers(s))
}
// moduleOfCarriers is ModuleOf over one way of finding the carriers.
func moduleOfCarriers(carriers func(ctx context.Context, name string) ([]Built, error)) func(ctx context.Context, name string) (module, artifact string, found bool, err error) { func moduleOfCarriers(carriers func(ctx context.Context, name string) ([]Built, error)) func(ctx context.Context, name string) (module, artifact string, found bool, err error) {
return func(ctx context.Context, name string) (string, string, bool, error) { return func(ctx context.Context, name string) (string, string, bool, error) {
got, err := carriers(ctx, name) got, err := carriers(ctx, name)
@@ -25,6 +25,8 @@ import (
const ( const (
OldFormState = "old-form" OldFormState = "old-form"
OldFormKey = "window" OldFormKey = "window"
// SaidOldFormClosed is the why of the build log's line saying the window closed (build.said).
SaidOldFormClosed = "old-form-closed"
) )
// OldFormHeld is the finding of a node holding the window open for FindingAfter, about that node, cleared when the // OldFormHeld is the finding of a node holding the window open for FindingAfter, about that node, cleared when the
@@ -9,23 +9,14 @@ import (
) )
// **A publish that ends badly is loud** (design 51 *Health and conditions*; review round 1): the builder raises the // **A publish that ends badly is loud** (design 51 *Health and conditions*; review round 1): the builder raises the
// finding publish-refused when a holder says refused, and publish-unanswered when a version it built and numbered is // finding publish-refused when a holder says refused, about the name, so a later published of any version of it clears
// neither published nor refused within PublishBound. Each is about the name, so a later published of any version of it // it. A seat's outcome that does not read is the finding seat-outcome-unread about the seat, cleared by its next outcome
// clears both. A seat's outcome that does not read is the finding seat-outcome-unread about the seat, cleared by its // that reads. A reserved version left unpublished past its bound is the reservation's finding (version-unreleased,
// next outcome that reads. // design 47 G §369); the numbered version's bound goes with the numbering from before G (design 47 H §756).
//
// The bound is a key of the builder's state bounds per version (PublishBoundKey), written with its own time to live
// when the build is done and the version is still numbered, deleted at the holder's word; the bus's marker of its end,
// heard on the watch, is what raises publish-unanswered while the version is still numbered. No timer.
const ( const (
// BoundsState is the builder's state of its expiring keys, each with its own time to live: a publish's bound // BoundsState is the builder's state of its expiring keys, each with its own time to live: a node's seven days holding the old form's window (OldFormBoundKey) and a build key left
// (PublishBoundKey), a node's seven days holding the old form's window (OldFormBoundKey) and a build key left
// building unput (UnputBoundKey). Its end, the bus's marker heard on the watch, is what acts. // building unput (UnputBoundKey). Its end, the bus's marker heard on the watch, is what acts.
BoundsState = "bounds" BoundsState = "bounds"
// PublishBound is the build module's own wait for the holder's word (design 51 *How a publish ends*: at most
// 10 minutes), so a version unanswered past it is one the holder never answered.
PublishBound = 10 * time.Minute
PublishRefused = "publish-refused" PublishRefused = "publish-refused"
PublishUnanswered = "publish-unanswered" PublishUnanswered = "publish-unanswered"
SeatOutcomeUnread = "seat-outcome-unread" SeatOutcomeUnread = "seat-outcome-unread"
@@ -33,7 +24,6 @@ const (
// The prefixes of the keys of BoundsState. // The prefixes of the keys of BoundsState.
const ( const (
publishBoundPrefix = "publish."
oldFormBoundPrefix = "old-form." oldFormBoundPrefix = "old-form."
unputBoundPrefix = "unput." unputBoundPrefix = "unput."
stepsBoundPrefix = "steps." stepsBoundPrefix = "steps."
@@ -62,16 +52,9 @@ func StepsBoundOf(key string) (module, askID string, ok bool) {
// UnputBoundOf is the build key an unput bound names, and whether key is one. // UnputBoundOf is the build key an unput bound names, and whether key is one.
func UnputBoundOf(key string) (string, bool) { return strings.CutPrefix(key, unputBoundPrefix) } func UnputBoundOf(key string) (string, bool) { return strings.CutPrefix(key, unputBoundPrefix) }
// PublishBoundKey is the bound of name's version: `publish.<versions key>`.
func PublishBoundKey(name, version string) string { return publishBoundPrefix + Key(name, version) }
// OldFormBoundKey is the bound of node's seven days holding the old form's window: `old-form.<node>`. // OldFormBoundKey is the bound of node's seven days holding the old form's window: `old-form.<node>`.
func OldFormBoundKey(node string) string { return oldFormBoundPrefix + EscapeToken(node) } func OldFormBoundKey(node string) string { return oldFormBoundPrefix + EscapeToken(node) }
// PublishBoundOf is the versions key a publish's bound names, and whether key is one; a key that is no publish's
// bound is an old form's (IsOldFormBound) or nothing the builder wrote.
func PublishBoundOf(key string) (string, bool) { return strings.CutPrefix(key, publishBoundPrefix) }
// IsOldFormBound says key is a node's bound of the old form's window: its end steps the window, which raises the // IsOldFormBound says key is a node's bound of the old form's window: its end steps the window, which raises the
// finding for every node past FindingAfter. // finding for every node past FindingAfter.
func IsOldFormBound(key string) bool { return strings.HasPrefix(key, oldFormBoundPrefix) } func IsOldFormBound(key string) bool { return strings.HasPrefix(key, oldFormBoundPrefix) }
@@ -81,7 +64,7 @@ const BoundsTool = "builder_bounds"
// BoundsDescription is builder_bounds' description. // BoundsDescription is builder_bounds' description.
const BoundsDescription = "The builder's expiring keys, its state " + BoundsState + " (design 51 *Health and conditions*): each key with what it " + const BoundsDescription = "The builder's expiring keys, its state " + BoundsState + " (design 51 *Health and conditions*): each key with what it " +
"bounds (a version's publish, whose end unanswered is the finding " + PublishUnanswered + "; or a node's seven days holding the old " + "bounds (a node's seven days holding the old " +
"form's window, whose end is the finding " + OldFormHeld + "; or a build key left building because its end could not be written, " + "form's window, whose end is the finding " + OldFormHeld + "; or a build key left building because its end could not be written, " +
"whose end is the finding call-unanswered; or a dependent's wait for a package member of a group's run, whose end fails its " + "whose end is the finding call-unanswered; or a dependent's wait for a package member of a group's run, whose end fails its " +
"step), when it ends, and how long is left. The bus ends each key by its own time to live." "step), when it ends, and how long is left. The bus ends each key by its own time to live."
@@ -37,9 +37,8 @@ const (
PublishQueueTool = "builder_publish_queue" PublishQueueTool = "builder_publish_queue"
// QueueFull is what version-unreleased says of a version the work queue's cap refused. // QueueFull is what version-unreleased says of a version the work queue's cap refused.
QueueFull = "queue full" QueueFull = "queue full"
// PublishDropTool and PublishFirstTool are builder_publish_drop and builder_publish_first (§793). // PublishDropTool is builder_publish_drop (§793); builder_publish_first is retired (H-A-483, third addendum).
PublishDropTool = "builder_publish_drop" PublishDropTool = "builder_publish_drop"
PublishFirstTool = "builder_publish_first"
// NotStoredWords opens what a refused artifact is said as. // NotStoredWords opens what a refused artifact is said as.
NotStoredWords = "not stored: " NotStoredWords = "not stored: "
// VerbPublish is the registry seats' verb a publish again sends, VerbVersions the one whose record says what a seat holds // VerbPublish is the registry seats' verb a publish again sends, VerbVersions the one whose record says what a seat holds
@@ -48,7 +47,7 @@ const (
VerbVersions = "versions" VerbVersions = "versions"
// PublishClassLive is the class of a publish whose build ended in this run, which a pipeline's build step waits on; // PublishClassLive is the class of a publish whose build ended in this run, which a pipeline's build step waits on;
// PublishClassStart that of a publish asked again at a start, of a build that ended before it. A holder's items are pulled // PublishClassStart that of a publish asked again at a start, of a build that ended before it. A holder's items are pulled
// live first, each class oldest first (design 47 H H-A-290 (1), H2 §793). // by its one consumer in the order they are put (design 47 H H-A-290 (1), H2 §793, H-A-483).
PublishClassLive = "live" PublishClassLive = "live"
PublishClassStart = "again" PublishClassStart = "again"
// PublishSendsAtOnce bounds the sends of one holder that run at once, its consumers' max ack pending (H-A-290 (3), §793). // PublishSendsAtOnce bounds the sends of one holder that run at once, its consumers' max ack pending (H-A-290 (3), §793).
@@ -97,21 +96,19 @@ type QueuedPublish struct {
Class string `json:"class,omitempty"` Class string `json:"class,omitempty"`
} }
// rank is the place of q's class in a holder's queue: the live first. // streamOrder sorts the keys of the work queue's items in stream order: each key is its item's stream sequence (the builder's
func (q QueuedPublish) rank() int { // reader, publishitem.go), compared as a number; a key that is no number sorts after them by its words.
if q.Class == PublishClassLive { func streamOrder(keys []string) {
return 0 sort.SliceStable(keys, func(i, j int) bool {
} a, aerr := strconv.ParseUint(keys[i], 10, 64)
return 1 b, berr := strconv.ParseUint(keys[j], 10, 64)
} switch {
case aerr == nil && berr == nil:
// sortQueued sorts a holder's queued versions in the order they are sent: the live class first, each class oldest first.
func sortQueued(qs []QueuedPublish) {
sort.SliceStable(qs, func(i, j int) bool {
if a, b := qs[i].rank(), qs[j].rank(); a != b {
return a < b return a < b
case aerr == nil || berr == nil:
return aerr == nil
} }
return qs[i].Queued.Before(qs[j].Queued) return keys[i] < keys[j]
}) })
} }
@@ -456,7 +453,7 @@ func (r *Republisher) Republish(ctx context.Context, module, version string) ([]
type Queued struct { type Queued struct {
Total int `json:"total"` Total int `json:"total"`
Counts []QueueCount `json:"counts"` Counts []QueueCount `json:"counts"`
// Queue are the first queued versions, per holder in the order they are sent (the live class first, each class oldest first); // Queue are the first queued versions, in stream order, the order each holder's one consumer gives them (H-A-483);
// with a module named, only that module's. // with a module named, only that module's.
Queue []QueuedPublish `json:"queue"` Queue []QueuedPublish `json:"queue"`
// Listed says how many of Total the answer lists. // Listed says how many of Total the answer lists.
@@ -512,7 +509,8 @@ func PublishItemKey(module, version string) string {
// PublishQueueOf is the seat mesh-builds' verb publish-queue (design 47 H2 §793; H-A-454): the builder's read of its own work queue // PublishQueueOf is the seat mesh-builds' verb publish-queue (design 47 H2 §793; H-A-454): the builder's read of its own work queue
// publishes (queue, its items read in bulk, capped past its bound), small at any size of the queue (H-A-290 (5)): the items' count // publishes (queue, its items read in bulk, capped past its bound), small at any size of the queue (H-A-290 (5)): the items' count
// per holder and class with the oldest and newest queue time, and the first PublishQueueListCap in the order they are sent; module // per holder and class with the oldest and newest queue time, and the first PublishQueueListCap in stream order, the order the
// holder's one consumer gives them (H-A-483, third addendum); module
// (and version) narrow the list to one module's (one version's), so an item's class can be read. // (and version) narrow the list to one module's (one version's), so an item's class can be read.
func PublishQueueOf(queue Reader, module, version string) (meshbuilds.PublishQueueAnswer, error) { func PublishQueueOf(queue Reader, module, version string) (meshbuilds.PublishQueueAnswer, error) {
out := meshbuilds.PublishQueueAnswer{Counts: []meshbuilds.PublishQueueAnswerCountsItem{}, Queue: []meshbuilds.PublishQueueAnswerQueueItem{}} out := meshbuilds.PublishQueueAnswer{Counts: []meshbuilds.PublishQueueAnswerCountsItem{}, Queue: []meshbuilds.PublishQueueAnswerQueueItem{}}
@@ -525,7 +523,13 @@ func PublishQueueOf(queue Reader, module, version string) (meshbuilds.PublishQue
} }
counts := map[[2]string]*meshbuilds.PublishQueueAnswerCountsItem{} counts := map[[2]string]*meshbuilds.PublishQueueAnswerCountsItem{}
var listed []QueuedPublish var listed []QueuedPublish
for _, raw := range vals { keys := make([]string, 0, len(vals))
for k := range vals {
keys = append(keys, k)
}
streamOrder(keys)
for _, k := range keys {
raw := vals[k]
var q QueuedPublish var q QueuedPublish
if json.Unmarshal(raw, &q) != nil { if json.Unmarshal(raw, &q) != nil {
continue continue
@@ -559,25 +563,12 @@ func PublishQueueOf(queue Reader, module, version string) (meshbuilds.PublishQue
} }
return out.Counts[i].Class < out.Counts[j].Class return out.Counts[i].Class < out.Counts[j].Class
}) })
sort.SliceStable(listed, func(i, j int) bool { return listed[i].Holder < listed[j].Holder })
byHolder := map[string][]QueuedPublish{}
var holders []string
for _, q := range listed { for _, q := range listed {
if byHolder[q.Holder] == nil { if len(out.Queue) == PublishQueueListCap {
holders = append(holders, q.Holder) break
}
byHolder[q.Holder] = append(byHolder[q.Holder], q)
}
for _, h := range holders {
qs := byHolder[h]
sortQueued(qs)
for _, q := range qs {
if len(out.Queue) == PublishQueueListCap {
break
}
out.Queue = append(out.Queue, meshbuilds.PublishQueueAnswerQueueItem{Holder: q.Holder, Module: q.Module, Version: q.Version,
Class: q.Class, Artifacts: q.Artifacts, Queued: q.Queued})
} }
out.Queue = append(out.Queue, meshbuilds.PublishQueueAnswerQueueItem{Holder: q.Holder, Module: q.Module, Version: q.Version,
Class: q.Class, Artifacts: q.Artifacts, Queued: q.Queued})
} }
out.Listed = int64(len(out.Queue)) out.Listed = int64(len(out.Queue))
return out, nil return out, nil
@@ -631,20 +622,17 @@ func AnswerQueue(q meshbuilds.PublishQueueAnswer, acted, reasks Reader) (Queued,
// PublishQueueDescription is builder_publish_queue's description. // PublishQueueDescription is builder_publish_queue's description.
const PublishQueueDescription = "The versions the builder will publish again (its work queue " + PublishesLocal + ", design 47 G section 588, H2 section 793): " + const PublishQueueDescription = "The versions the builder will publish again (its work queue " + PublishesLocal + ", design 47 G section 588, H2 section 793): " +
"how many each registry seat holder's items hold per class (live, a build a pipeline's step waits on, pulled first, or again, asked again at a start) " + "how many each registry seat holder's items hold per class (live, a build a pipeline's step waits on, or again, asked again at a start) " +
"with the oldest and newest queue time; the first 50 in the order they are pulled, each with its class, its artifacts' digests and when it was " + "with the oldest and newest queue time; the first 50 in stream order, the order each holder's one consumer pulls them, each with its class, its artifacts' digests and when it was " +
"queued (module, and version, list only that module's, so one item's class can be read); the keys of the state " + ActedState + ", the last stream " + "queued (module, and version, list only that module's, so one item's class can be read); the keys of the state " + ActedState + ", the last stream " +
"sequence the builder acted on for each subject; and the publish items (design 47 G A-457a), counted, the first 50 by next try, each version's " + "sequence the builder acted on for each subject; and the publish items (design 47 G A-457a), counted, the first 50 by next try, each version's " +
"tries and next try, and why one ended (its tries spent, or dropped). A read past its pages is answered capped, naming the items read and the " + "tries and next try, and why one ended (its tries spent, or dropped). A read past its pages is answered capped, naming the items read and the " +
"queue's size (H-A-293). Read-only." "queue's size (H-A-293). Read-only."
// PublishDropDescription and PublishFirstDescription are builder_publish_drop's and builder_publish_first's (§793). // PublishDropDescription is builder_publish_drop's (§793).
const PublishDropDescription = "Drop one version's publish (design 47 H2 section 793): its items on the work queue " + PublishesLocal + " are " + const PublishDropDescription = "Drop one version's publish (design 47 H2 section 793): its items on the work queue " + PublishesLocal + " are " +
"terminated at every holder, and its publish item ended with who dropped it and why, so it is never sent or put again; builder_publish_again " + "terminated at every holder, and its publish item ended with who dropped it and why, so it is never sent or put again; builder_publish_again " +
"asks it anew. A hand act, recorded in the hand-act log first." "asks it anew. A hand act, recorded in the hand-act log first."
const PublishFirstDescription = "Put one version's publish first (design 47 H2 section 793): each of its again items on the work queue " +
PublishesLocal + " is put again as live, under the message id <holder>.live.<module>.<version>, pulled before every again item, and the old " +
"terminated. A hand act, recorded in the hand-act log first."
// PublishAgainDescription is builder_publish_again's description. // PublishAgainDescription is builder_publish_again's description.
const PublishAgainDescription = "Publish reserved versions again (design 47 G section 588), which builds nothing: with module and version, that reserved " + const PublishAgainDescription = "Publish reserved versions again (design 47 G section 588), which builds nothing: with module and version, that reserved " +
@@ -855,11 +843,6 @@ func (r *Reserver) MarkUnstored(ctx context.Context, module, version, artifact,
} }
} }
// UnheardBound is how many messages the builder's durable on the events stream may hold pending and unacknowledged while a
// publish is asked again (design 47 H H-A-269 (2), H-A-272): at or above it a published of the version may still be unheard, so
// the try is skipped. A constant of the builder, no setting.
const UnheardBound = 100
// HeldVersion is one version a registry seat's verb versions answers of a name, with its digest. // HeldVersion is one version a registry seat's verb versions answers of a name, with its digest.
type HeldVersion struct { type HeldVersion struct {
Version, Digest string Version, Digest string
@@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"maps" "maps"
"slices" "slices"
"strconv"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@@ -101,10 +102,8 @@ func (b *republishBed) reserve(t *testing.T, module string) ReservedVersion {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
for ref, d := range map[string]string{module + ":prog": "sha256:aa", module + ":lib": "sha256:bb"} { if _, _, err := b.Reserved.Built(ctx, module, v.Version, map[string]string{module + ":prog": "sha256:aa", module + ":lib": "sha256:bb"}, nil); err != nil {
if _, err := b.Reserved.Built(ctx, module, v.Version, ref, d, nil); err != nil { t.Fatal(err)
t.Fatal(err)
}
} }
b.now = b.now.Add(UnreleasedBound + time.Minute) b.now = b.now.Add(UnreleasedBound + time.Minute)
return v return v
@@ -404,8 +403,9 @@ func answerOf(queue, acted, reasks Reader, module, version string) (Queued, erro
} }
// TestThePublishQueueToolAnswersAtAnySize: design 47 H H-A-290 (5) — builder_publish_queue over two thousand queued versions answers // TestThePublishQueueToolAnswersAtAnySize: design 47 H H-A-290 (5) — builder_publish_queue over two thousand queued versions answers
// within a second and small: counts per holder and class with the oldest and newest queue time, a list capped at fifty in the // within a second and small: counts per holder and class with the oldest and newest queue time, a list capped at fifty in stream
// order they are sent, and one module's item with its class; each state read in bulk where the reader can. // order (H-A-483, third addendum: each key is its item's stream sequence), and one module's item with its class; each state read
// in bulk where the reader can.
func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) { func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) {
at := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC) at := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
vals := map[string]json.RawMessage{} vals := map[string]json.RawMessage{}
@@ -418,7 +418,7 @@ func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) {
class = PublishClassLive class = PublishClassLive
} }
q := QueuedPublish{V: 1, Holder: holder, Module: fmt.Sprintf("m%d", i), Version: "0.1.0", Artifacts: map[string]string{"a": "sha256:aa"}, Queued: at.Add(time.Duration(i) * time.Second), Class: class} q := QueuedPublish{V: 1, Holder: holder, Module: fmt.Sprintf("m%d", i), Version: "0.1.0", Artifacts: map[string]string{"a": "sha256:aa"}, Queued: at.Add(time.Duration(i) * time.Second), Class: class}
vals[QueueKey(holder, q.Module, q.Version)], _ = json.Marshal(q) vals[strconv.Itoa(i+1)], _ = json.Marshal(q) // the reader keys each item by its stream sequence
} }
gets := 0 gets := 0
queue := Reader{All: func() (StatePage, error) { return StatePage{Values: vals}, nil }, queue := Reader{All: func() (StatePage, error) { return StatePage{Values: vals}, nil },
@@ -435,8 +435,10 @@ func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) {
if fmt.Sprintln(a.Counts[1].Holder, a.Counts[1].Class, a.Counts[1].Count, a.Counts[1].Oldest.Equal(at.Add(1991*time.Second)), a.Counts[1].Newest.Equal(at.Add(1999*time.Second))) != "go "+PublishClassLive+" 5 true true\n" || len(a.Counts) != 4 { if fmt.Sprintln(a.Counts[1].Holder, a.Counts[1].Class, a.Counts[1].Count, a.Counts[1].Oldest.Equal(at.Add(1991*time.Second)), a.Counts[1].Newest.Equal(at.Add(1999*time.Second))) != "go "+PublishClassLive+" 5 true true\n" || len(a.Counts) != 4 {
t.Errorf("counts %+v, want per holder and class with their oldest and newest", a.Counts) t.Errorf("counts %+v, want per holder and class with their oldest and newest", a.Counts)
} }
if a.Queue[0].Class != PublishClassLive || a.Queue[0].Holder != "go" { for i, q := range a.Queue {
t.Errorf("the list opens with %+v, want the go holder's live class, sent first", a.Queue[0]) if q.Module != fmt.Sprintf("m%d", i) {
t.Fatalf("the list holds %s at %d, want m%d: the items in stream order, whatever their holder or class", q.Module, i, i)
}
} }
one, err := answerOf(queue, none, none, "m1995", "") one, err := answerOf(queue, none, none, "m1995", "")
if err != nil || len(one.Queue) != 1 || one.Queue[0].Class != PublishClassLive || one.Total != 2000 { if err != nil || len(one.Queue) != 1 || one.Queue[0].Class != PublishClassLive || one.Total != 2000 {
@@ -6,14 +6,13 @@ import (
"errors" "errors"
"fmt" "fmt"
"maps" "maps"
"reflect"
"slices" "slices"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
) )
@@ -42,8 +41,8 @@ const (
// VersionHeldElsewhere is the finding of a number a registry seat already holds, skipped at reserving or moved from (design 47 // VersionHeldElsewhere is the finding of a number a registry seat already holds, skipped at reserving or moved from (design 47
// H H-A-275), scope module. // H H-A-275), scope module.
VersionHeldElsewhere = "version-held-elsewhere" VersionHeldElsewhere = "version-held-elsewhere"
// VersionTaggedElsewhere is the finding of a number whose git tag stands at another commit, skipped at reserving (design 47 // VersionTaggedElsewhere is the finding of a number whose git tag stood at another commit, which a reserve skipped before no
// H2 §796), scope module; cleared at the module's next version-released. // tag was read (design 47 H2 H-A-494); one raised before is cleared at the module's next version-released.
VersionTaggedElsewhere = "version-tagged-elsewhere" VersionTaggedElsewhere = "version-tagged-elsewhere"
) )
@@ -55,6 +54,10 @@ type ReservedVersion struct {
Version string `json:"version"` // MAJOR.MINOR.PATCH Version string `json:"version"` // MAJOR.MINOR.PATCH
// Artifacts are the module's artifacts at the version: the digest once built, empty before. // Artifacts are the module's artifacts at the version: the digest once built, empty before.
Artifacts map[string]string `json:"artifacts"` Artifacts map[string]string `json:"artifacts"`
// Upstream are the artifacts of kind upstream, by reference (design 47 H2 H-A-486): kept in Artifacts with their digest for the
// record, never awaited, as design 51 copies an upstream image by its pinned digest and no registry seat says it published at
// a version. A reservation written before carries none.
Upstream []string `json:"upstream,omitempty"`
// BuiltAt is when the build ended with every digest known; the publish's bound counts from it. // BuiltAt is when the build ended with every digest known; the publish's bound counts from it.
BuiltAt time.Time `json:"built-at,omitzero"` BuiltAt time.Time `json:"built-at,omitzero"`
// Published are the artifacts a registry seat said published at this version with the built digest. // Published are the artifacts a registry seat said published at this version with the built digest.
@@ -63,8 +66,8 @@ type ReservedVersion struct {
// was kept. // was kept.
PublishedAt map[string]time.Time `json:"published-at,omitempty"` PublishedAt map[string]time.Time `json:"published-at,omitempty"`
At time.Time `json:"at"` At time.Time `json:"at"`
// Repository and Commit are what the build was made from, and Tag the git tag its release is written as (a Go // Repository and Commit are what the build was made from. Tag is kept for a reservation written before design 47 H2 H-A-494:
// package's, GoTagOf): empty for a module with no Go package (design 47 G §370), or whose Go package's directory is not known. // no git tag is written at a release any more, and a new reservation names none.
Repository string `json:"repository,omitempty"` Repository string `json:"repository,omitempty"`
Commit string `json:"commit,omitempty"` Commit string `json:"commit,omitempty"`
Tag string `json:"tag,omitempty"` Tag string `json:"tag,omitempty"`
@@ -110,22 +113,19 @@ type KeptPublished struct {
Digest string `json:"digest"` Digest string `json:"digest"`
} }
// Source is what a build reserving a version is made from (design 47 G §370): the repository and commit the git tag is // Source is what a build reserving a version is made from (design 47 G §370): the repository and commit, kept on the reservation.
// written at, and whether the module has a Go package, whose version is tagged.
type Source struct { type Source struct {
Repository, Commit string Repository, Commit string
// Fingerprint is the fingerprint of the catalog entry the build is made from (design 47 G A-76). // Fingerprint is the fingerprint of the catalog entry the build is made from (design 47 G A-76).
Fingerprint string Fingerprint string
GoPackage bool
// GoArtifact is the artifact that is the module's Go package, whose module path names the directory its tag is written in
// (design 47 H2 §796).
GoArtifact string
// Branch is the watched branch of the catalog revision whose entry the build came from, and Revision the source revision of // Branch is the watched branch of the catalog revision whose entry the build came from, and Revision the source revision of
// that catalog revision (design 47 G §371, A-57), kept on the reservation for the publication. // that catalog revision (design 47 G §371, A-57), kept on the reservation for the publication.
Branch string Branch string
Revision int64 Revision int64
// CatalogRevision is the catalog revision number the build's step ask named (H-A-218), 0 when none did. // CatalogRevision is the catalog revision number the build's step ask named (H-A-218), 0 when none did.
CatalogRevision int64 CatalogRevision int64
// Upstream are the artifacts of kind upstream among those reserved, by reference (H-A-486), kept on the reservation.
Upstream []string
// Rebuild marks a build again of a done key whose version is not released: the standing reservation of Fingerprint is replaced // Rebuild marks a build again of a done key whose version is not released: the standing reservation of Fingerprint is replaced
// and is no floor, so the number is the next above the catalog's highest alone (design 47 G A-490b). // and is no floor, so the number is the next above the catalog's highest alone (design 47 G A-490b).
Rebuild bool Rebuild bool
@@ -134,9 +134,6 @@ type Source struct {
// ReservedKey is the key of module's reservation of series (MAJOR.MINOR). // ReservedKey is the key of module's reservation of series (MAJOR.MINOR).
func ReservedKey(module, series string) string { return Key(module, series) } func ReservedKey(module, series string) string { return Key(module, series) }
// ErrNotFilled is what Reserve answers before the catalog says versions-filled: nothing is reserved until then (§369).
var ErrNotFilled = errors.New("versions-filled is not heard: nothing is reserved before the catalog's versions are filled")
// ReserveStore is the reservations' bucket: compare-and-set, and deletion. // ReserveStore is the reservations' bucket: compare-and-set, and deletion.
type ReserveStore interface { type ReserveStore interface {
Store Store
@@ -148,8 +145,6 @@ type Reserver struct {
Store ReserveStore Store ReserveStore
// ReleasedOf are the patch versions (MAJOR.MINOR.PATCH) the catalog holds released for module, from its verb versions. // ReleasedOf are the patch versions (MAJOR.MINOR.PATCH) the catalog holds released for module, from its verb versions.
ReleasedOf func(ctx context.Context, module string) ([]string, error) ReleasedOf func(ctx context.Context, module string) ([]string, error)
// Filled says the catalog said versions-filled.
Filled func() bool
// Took is told when a build took over the series' reservation of an older build never released (design 47 G A-455): the // Took is told when a build took over the series' reservation of an older build never released (design 47 G A-455): the
// older reservation, which no want follows any more, is gone from the key, replaced by the newer's. Nil is told none. // older reservation, which no want follows any more, is gone from the key, replaced by the newer's. Nil is told none.
Took func(ctx context.Context, older, newer ReservedVersion) Took func(ctx context.Context, older, newer ReservedVersion)
@@ -171,92 +166,6 @@ type Reserver struct {
HeldNumbers func(ctx context.Context, module, fingerprint string, refs []string) ([]string, error) HeldNumbers func(ctx context.Context, module, fingerprint string, refs []string) ([]string, error)
// HeldElsewhere is told the numbers of module a reserve skipped because a registry holds them (H-A-275); nil is told none. // HeldElsewhere is told the numbers of module a reserve skipped because a registry holds them (H-A-275); nil is told none.
HeldElsewhere func(ctx context.Context, module string, skipped []string) HeldElsewhere func(ctx context.Context, module string, skipped []string)
// Names answers a Go package's module path, which names the directory its tag is written in (design 47 H2 §796); nil, or a
// name not known, tags the version nowhere, said.
Names PackageNames
// Tags reads repository's tags starting with prefix, each with the commit it names, through the seat git's tags (design 47
// H2 §796); away says the read met a transport fault or the error kind away, which lets the reservation go on, said. Nil
// reads none.
Tags func(ctx context.Context, repository, prefix string) (tags []git.Tag, away bool, err error)
// TaggedElsewhere is told the numbers of module a reserve skipped because their tag stands at another commit (§796); nil
// is told none.
TaggedElsewhere func(ctx context.Context, module string, skipped []string)
tagsMu sync.Mutex
// tagsRead are the tags last read of each module, by series patch to the commit, with the catalog revision they were read
// under: a module's tags are read once per catalog revision it reserves under (§796).
tagsRead map[string]tagsAt
}
// tagsAt are a module's tags of one series read under one catalog revision: patch to the commit its tag names.
type tagsAt struct {
revision, prefix string
commits map[int]string
}
// goDirectory is the directory of module's Go package in its repository (§796), from its module path; ok is false, said, when
// no name or no directory of the repository is known.
func (r *Reserver) goDirectory(ctx context.Context, module string, src Source) (string, bool) {
if r.Names == nil {
return "", false
}
path, known, err := r.Names(ctx, module, src.GoArtifact)
switch {
case err != nil:
r.said(fmt.Errorf("%s: its Go package's name cannot be read, so its version is tagged nowhere: %w", module, err))
return "", false
case !known:
r.said(fmt.Errorf("%s: no name of its Go package %s is known yet, so its version is tagged nowhere", module, src.GoArtifact))
return "", false
}
dir, ok := GoDirectory(path, src.Repository)
if !ok {
r.said(fmt.Errorf("%s: its Go package %s is not a module path of the repository %s, so its version is tagged nowhere", module, path, src.Repository))
}
return dir, ok
}
// taggedAt are the patches of series whose tag `<directory>/v<series>.<patch>` stands, each with its commit, read once per
// catalog revision the module reserves under (§796). A read that meets a transport fault or away answers none, said, and the
// reservation goes on; any other failure refuses the reservation, naming it.
func (r *Reserver) taggedAt(ctx context.Context, module, series, dir string, src Source) (map[int]string, error) {
if r.Tags == nil {
return nil, nil
}
prefix := TagPrefix(dir) + series + "."
revision := ""
if src.CatalogRevision > 0 {
revision = fmt.Sprintf("%s.%d", src.Branch, src.CatalogRevision)
r.tagsMu.Lock()
got, ok := r.tagsRead[module]
r.tagsMu.Unlock()
if ok && got.revision == revision && got.prefix == prefix {
return got.commits, nil
}
}
tags, away, err := r.Tags(ctx, src.Repository, prefix)
if err != nil && away {
r.said(fmt.Errorf("%s: its tags %s* cannot be read (%w), so the reservation goes on without them", module, prefix, err))
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("the tags %s* of %s cannot be read: %w", prefix, module, err)
}
commits := map[int]string{}
for _, t := range tags {
if s, p, err := SplitVersion(strings.TrimPrefix(t.Tag, TagPrefix(dir))); err == nil && s == series && strings.HasPrefix(t.Tag, prefix) {
commits[p] = t.Commit
}
}
if revision != "" {
r.tagsMu.Lock()
if r.tagsRead == nil {
r.tagsRead = map[string]tagsAt{}
}
r.tagsRead[module] = tagsAt{revision: revision, prefix: prefix, commits: commits}
r.tagsMu.Unlock()
}
return commits, nil
} }
// heldNumbers are the patches of series a registry holds of module's artifacts (H-A-275); a read that fails is said, and none. // heldNumbers are the patches of series a registry holds of module's artifacts (H-A-275); a read that fails is said, and none.
@@ -277,19 +186,15 @@ func (r *Reserver) heldNumbers(ctx context.Context, module, series, fingerprint
return out return out
} }
// nextFree is the first patch after after that no registry holds and whose tag stands at no other commit than commit, with the // nextFree is the first patch after after that no registry holds, with the held numbers it skipped (H-A-275). No git tag is
// held numbers it skipped (H-A-275) and those tagged elsewhere (design 47 H2 §796). // read: a series is numbered from the catalog's versions and the registries' alone (design 47 H2 H-A-494).
func nextFree(series string, after int, held map[int]bool, tagged map[int]string, commit string) (int, []string, []string) { func nextFree(series string, after int, held map[int]bool) (int, []string) {
var skipped, elsewhere []string var skipped []string
for p := after + 1; ; p++ { for p := after + 1; ; p++ {
switch c, ok := tagged[p]; { if !held[p] {
case held[p]: return p, skipped
skipped = append(skipped, fmt.Sprintf("%s.%d", series, p))
case ok && c != commit:
elsewhere = append(elsewhere, fmt.Sprintf("%s.%d (tagged at %s)", series, p, c))
default:
return p, skipped, elsewhere
} }
skipped = append(skipped, fmt.Sprintf("%s.%d", series, p))
} }
} }
@@ -327,9 +232,6 @@ func SplitVersion(version string) (series string, patch int, err error) {
// alike (design 47 H H-A-225, which amends G A-490b): the run already building carries that number. A reservation another // alike (design 47 H H-A-225, which amends G A-490b): the run already building carries that number. A reservation another
// fingerprint takes over is withdrawn: its version is kept in Withdrawn, and Took is told so the older build is ended. // fingerprint takes over is withdrawn: its version is kept in Withdrawn, and Took is told so the older build is ended.
func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts []string, src Source) (ReservedVersion, error) { func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts []string, src Source) (ReservedVersion, error) {
if r.Filled != nil && !r.Filled() {
return ReservedVersion{}, ErrNotFilled
}
released, err := r.ReleasedOf(ctx, module) released, err := r.ReleasedOf(ctx, module)
if err != nil { if err != nil {
return ReservedVersion{}, fmt.Errorf("the released versions of %s cannot be read: %w", module, err) return ReservedVersion{}, fmt.Errorf("the released versions of %s cannot be read: %w", module, err)
@@ -342,15 +244,6 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts
} }
key := ReservedKey(module, series) key := ReservedKey(module, series)
held := r.heldNumbers(ctx, module, series, src.Fingerprint, artifacts) held := r.heldNumbers(ctx, module, series, src.Fingerprint, artifacts)
dir, tagged := "", false
var tags map[int]string
if src.GoPackage {
if dir, tagged = r.goDirectory(ctx, module, src); tagged {
if tags, err = r.taggedAt(ctx, module, series, dir, src); err != nil {
return ReservedVersion{}, err
}
}
}
for { for {
cur, rev, found, err := r.get(ctx, key) cur, rev, found, err := r.get(ctx, key)
if err != nil { if err != nil {
@@ -368,15 +261,13 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts
next = p next = p
} }
} }
patch, skipped, elsewhere := nextFree(series, next, held, tags, src.Commit) patch, skipped := nextFree(series, next, held)
out := ReservedVersion{V: 1, Module: module, Series: series, Version: fmt.Sprintf("%s.%d", series, patch), Artifacts: map[string]string{}, At: r.now(), out := ReservedVersion{V: 1, Module: module, Series: series, Version: fmt.Sprintf("%s.%d", series, patch), Artifacts: map[string]string{}, At: r.now(),
Repository: src.Repository, Commit: src.Commit, Fingerprint: src.Fingerprint, Branch: src.Branch, Source: src.Revision, Revision: src.CatalogRevision} Repository: src.Repository, Commit: src.Commit, Fingerprint: src.Fingerprint, Branch: src.Branch, Source: src.Revision, Revision: src.CatalogRevision}
if tagged {
out.Tag = GoTagOf(dir, out.Version)
}
for _, a := range artifacts { for _, a := range artifacts {
out.Artifacts[a] = "" out.Artifacts[a] = ""
} }
out.Upstream = slices.Clone(src.Upstream)
if found { if found {
out.Withdrawn = maps.Clone(cur.Withdrawn) out.Withdrawn = maps.Clone(cur.Withdrawn)
if cur.Fingerprint != src.Fingerprint { if cur.Fingerprint != src.Fingerprint {
@@ -410,9 +301,6 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts
if len(skipped) > 0 && r.HeldElsewhere != nil { if len(skipped) > 0 && r.HeldElsewhere != nil {
r.HeldElsewhere(ctx, module, skipped) r.HeldElsewhere(ctx, module, skipped)
} }
if len(elsewhere) > 0 && r.TaggedElsewhere != nil {
r.TaggedElsewhere(ctx, module, elsewhere)
}
if found && r.Took != nil { if found && r.Took != nil {
r.Took(ctx, cur, out) r.Took(ctx, cur, out)
} }
@@ -467,39 +355,55 @@ func (r *Reserver) Withdraw(ctx context.Context, module, version string) (Reserv
} }
} }
// Built records artifact's digest under the reserved version of module's series; once every artifact has one the build is // Built records the digests of the artifacts built under the reserved version of module's series, by reference, with what each
// ended (BuiltAt). A reservation moved on to another version (a newer build took the next) is left alone and answers false. // resolved and was built with, in one compare-and-set of the reservation and one reindex for all of them (issue 1984 note 8,
func (r *Reserver) Built(ctx context.Context, module, version, artifact, digest string, deps []meshbuilds.Dependency) (bool, error) { // 1984/AC4): an artifact recorded already with its digest (and the dependencies given, when any are) is skipped, so a record
// tried again after one that timed out writes only what that one left, and nothing when every digest stands recorded. Once every
// artifact has one the build is ended (BuiltAt). It answers the reservation as it stands after the record; a reservation moved on
// to another version (a newer build took the next) is left alone and answers false.
func (r *Reserver) Built(ctx context.Context, module, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) (ReservedVersion, bool, error) {
series, _, err := SplitVersion(version) series, _, err := SplitVersion(version)
if err != nil { if err != nil {
return false, err return ReservedVersion{}, false, err
} }
key := ReservedKey(module, series) key := ReservedKey(module, series)
for { for {
cur, rev, found, err := r.get(ctx, key) cur, rev, found, err := r.get(ctx, key)
if err != nil || !found || cur.Version != version { if err != nil || !found || cur.Version != version {
return false, err return ReservedVersion{}, false, err
} }
was := cur was := cur
was.Artifacts = maps.Clone(cur.Artifacts) was.Artifacts = maps.Clone(cur.Artifacts)
cur.Artifacts[artifact] = digest if cur.Artifacts == nil {
if len(deps) > 0 { cur.Artifacts = map[string]string{}
if cur.Dependencies == nil { }
cur.Dependencies = map[string][]meshbuilds.Dependency{} changed := false
for ref, d := range digests {
if have, ok := cur.Artifacts[ref]; ok && have == d && (len(deps[ref]) == 0 || reflect.DeepEqual(cur.Dependencies[ref], deps[ref])) {
continue // recorded already (1984/AC4)
}
cur.Artifacts[ref], changed = d, true
if len(deps[ref]) > 0 {
if cur.Dependencies == nil {
cur.Dependencies = map[string][]meshbuilds.Dependency{}
}
cur.Dependencies[ref] = deps[ref]
} }
cur.Dependencies[artifact] = deps
} }
if cur.BuiltAt.IsZero() && allSet(cur.Artifacts) { if cur.BuiltAt.IsZero() && allSet(cur.Artifacts) {
cur.BuiltAt = r.now() cur.BuiltAt, changed = r.now(), true
}
if !changed {
return cur, true, nil
} }
raw, _ := json.Marshal(cur) raw, _ := json.Marshal(cur)
if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) { if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) {
continue continue
} else if err != nil { } else if err != nil {
return false, fmt.Errorf("%s cannot be written: %w", key, err) return ReservedVersion{}, false, fmt.Errorf("%s cannot be written: %w", key, err)
} }
r.said(r.reindex(ctx, key, was, cur)) r.said(r.reindex(ctx, key, was, cur))
return true, nil return cur, true, nil
} }
} }
@@ -529,6 +433,14 @@ type ReleasedBuild struct {
Version string `json:"version"` Version string `json:"version"`
// Digests are the published digest of each artifact, by reference (H-A-331); absent for a release kept before. // Digests are the published digest of each artifact, by reference (H-A-331); absent for a release kept before.
Digests map[string]string `json:"digests,omitempty"` Digests map[string]string `json:"digests,omitempty"`
// Withdrawn are the fingerprints whose numbers the released version took over, by the number withdrawn (H-A-226), so a
// takeover still answers once the release deleted the series key (H-A-508); absent for a release that took none over.
Withdrawn map[string]string `json:"withdrawn,omitempty"`
// Branch and Source are the source revision of the catalog revision the released build came from, as the key's origin names
// it (its watched branch with it), as its reservation kept them (design 47 H2 H-A-551, H-A-558 (2)): an importer's build of
// that origin is filled from it once the reservation is gone; empty for a release kept before.
Branch string `json:"branch,omitempty"`
Source int64 `json:"source,omitempty"`
} }
// ReleasedFor says whether the builder saw a version released for the build of fingerprint among the module's last releases. // ReleasedFor says whether the builder saw a version released for the build of fingerprint among the module's last releases.
@@ -598,8 +510,49 @@ func (r *Reserver) PublishedOf(ctx context.Context, module, artifact, fingerprin
return meshbuilds.PublishedAnswer{Published: false}, nil return meshbuilds.PublishedAnswer{Published: false}, nil
} }
// VersionAt answers the version artifact of module is published at from the source revision of branch (design 47 H2 H-A-547
// (3), H-A-551): the standing reservation of that branch and source revision whose artifact a registry seat said published, its
// number not withdrawn, first; else the module's release recorded at that branch and source revision (H-A-558 (2)), the newest such. A reservation of
// that origin not yet published answers none, so the importer's build waits for the publish (H-A-521).
func (r *Reserver) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) {
if module == "" || artifact == "" || source <= 0 {
return "", false, nil
}
ref := module + ":" + artifact
keys, err := r.Store.KeysOf(ctx, NameFilter(module))
if err != nil {
return "", false, fmt.Errorf("the reservations of %s cannot be listed: %w", module, err)
}
sort.Strings(keys)
for _, k := range keys {
cur, _, found, err := r.get(ctx, k)
if err != nil {
return "", false, err
}
if found && cur.Module == module && cur.Branch == branch && cur.Source == source && cur.Published[ref] && !hasKey(cur.Withdrawn, cur.Version) {
return cur.Version, true, nil
}
}
if r.Releases == nil {
return "", false, nil
}
raw, _, found, err := r.Releases.Get(ctx, ReleasedKey(module))
if err != nil {
return "", false, fmt.Errorf("the releases of %s cannot be read: %w", module, err)
}
var rec ReleasedRecord
if found && json.Unmarshal(raw, &rec) == nil {
for i := len(rec.Kept) - 1; i >= 0; i-- {
if rec.Kept[i].Branch == branch && rec.Kept[i].Source == source {
return rec.Kept[i].Version, true, nil
}
}
}
return "", false, nil
}
// keepRelease adds a release to the module's record, dropping the oldest past ReleasedKept. // keepRelease adds a release to the module's record, dropping the oldest past ReleasedKept.
func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version string, digests map[string]string) error { func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version string, digests, withdrawn map[string]string, branch string, source int64) error {
n := r.ReleasedKept n := r.ReleasedKept
if n < 1 { if n < 1 {
n = DefaultReleasedKept n = DefaultReleasedKept
@@ -619,7 +572,7 @@ func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version
kept = append(kept, k) kept = append(kept, k)
} }
} }
kept = append(kept, ReleasedBuild{Fingerprint: fingerprint, Version: version, Digests: digests}) kept = append(kept, ReleasedBuild{Fingerprint: fingerprint, Version: version, Digests: digests, Withdrawn: maps.Clone(withdrawn), Branch: branch, Source: source})
if len(kept) > n { if len(kept) > n {
kept = kept[len(kept)-n:] kept = kept[len(kept)-n:]
} }
@@ -636,6 +589,17 @@ func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version
} }
} }
// Holds answers whether a reservation holds module's version, from the one key of its series (design 47 H2 H-A-514
// addendum): a version-released of a version none holds is acknowledged at once, never by listing the module's keys.
func (r *Reserver) Holds(ctx context.Context, module, version string) (bool, error) {
series, _, err := SplitVersion(version)
if err != nil {
return false, err
}
cur, _, found, err := r.get(ctx, ReservedKey(module, series))
return found && cur.Version == version, err
}
// Released takes the catalog's version-released in: the key of that version is deleted, and every key of module's other // Released takes the catalog's version-released in: the key of that version is deleted, and every key of module's other
// series (the manifest moved on). A key holding a newer reserved version of the same series stays. It answers the keys // series (the manifest moved on). A key holding a newer reserved version of the same series stays. It answers the keys
// deleted. // deleted.
@@ -658,7 +622,7 @@ func (r *Reserver) Released(ctx context.Context, module, version string) ([]stri
continue continue
} }
if cur.Version == version && cur.Fingerprint != "" && r.Releases != nil { if cur.Version == version && cur.Fingerprint != "" && r.Releases != nil {
if err := r.keepRelease(ctx, module, cur.Fingerprint, version, cur.Artifacts); err != nil { if err := r.keepRelease(ctx, module, cur.Fingerprint, version, cur.Artifacts, cur.Withdrawn, cur.Branch, cur.Source); err != nil {
return gone, fmt.Errorf("the release of %s %s cannot be recorded: %w", module, version, err) return gone, fmt.Errorf("the release of %s %s cannot be recorded: %w", module, version, err)
} }
} }
@@ -730,7 +694,9 @@ func (r *Reserver) All(ctx context.Context) ([]ReservedVersion, error) {
} }
// TakenOver is the reservation of module's series whose withdrawn numbers hold one of the build of fingerprint (design 47 H // TakenOver is the reservation of module's series whose withdrawn numbers hold one of the build of fingerprint (design 47 H
// H-A-226), and whether there is one: the series moved to that reservation's fingerprint and version (H-A-244). // H-A-226), and whether there is one: the series moved to that reservation's fingerprint and version (H-A-244). Once that
// version is released and its series key deleted, the release record answers it, naming the fingerprints it withdrew
// (H-A-508): the newest such release, as a reservation of its fingerprint and version.
func (r *Reserver) TakenOver(ctx context.Context, module, fingerprint string) (ReservedVersion, bool, error) { func (r *Reserver) TakenOver(ctx context.Context, module, fingerprint string) (ReservedVersion, bool, error) {
all, err := r.All(ctx) all, err := r.All(ctx)
if err != nil { if err != nil {
@@ -746,6 +712,30 @@ func (r *Reserver) TakenOver(ctx context.Context, module, fingerprint string) (R
} }
} }
} }
if r.Releases == nil {
return ReservedVersion{}, false, nil
}
raw, _, found, err := r.Releases.Get(ctx, ReleasedKey(module))
if err != nil || !found {
return ReservedVersion{}, false, err
}
var rec ReleasedRecord
if err := json.Unmarshal(raw, &rec); err != nil {
// A record that cannot be read answers no "not taken over": the caller says it cannot judge (H-A-508).
return ReservedVersion{}, false, fmt.Errorf("the release record of %s cannot be read: %w", module, err)
}
for i := len(rec.Kept) - 1; i >= 0; i-- {
k := rec.Kept[i]
if k.Fingerprint == fingerprint {
continue
}
for _, fp := range k.Withdrawn {
if fp == fingerprint {
series, _, _ := SplitVersion(k.Version)
return ReservedVersion{V: 1, Module: module, Series: series, Version: k.Version, Fingerprint: k.Fingerprint}, true, nil
}
}
}
return ReservedVersion{}, false, nil return ReservedVersion{}, false, nil
} }
@@ -921,19 +911,32 @@ func (v ReservedVersion) keeps(name, digest string) bool {
return false return false
} }
// KeptTaken is what Kept took in: the reservation as the take-in left it (as written, or as read when nothing was kept on it),
// whether it stands built at the version, the artifacts newly marked and the kept published whose digest matched no artifact.
type KeptTaken struct {
Reserved ReservedVersion
Standing bool
Marked []Marked
Unmatched []KeptPublished
}
// Kept takes the published kept on module's reservation of version in once its build recorded every digest (design 47 G // Kept takes the published kept on module's reservation of version in once its build recorded every digest (design 47 G
// A-415): each kept published whose digest is an artifact's marks that artifact, as one heard after would, and every kept one // A-415): each kept published whose digest is an artifact's marks that artifact, as one heard after would, and every kept one
// leaves the reservation. It answers the artifacts newly marked and the kept published whose digest matched no artifact. // leaves the reservation. It answers the reservation as the take-in left it, so what follows the take-in is judged on the
func (r *Reserver) Kept(ctx context.Context, module, version string) ([]Marked, []KeptPublished, error) { // artifacts it marked (issue 1984 note 8, 1984/AC5).
func (r *Reserver) Kept(ctx context.Context, module, version string) (KeptTaken, error) {
series, _, err := SplitVersion(version) series, _, err := SplitVersion(version)
if err != nil { if err != nil {
return nil, nil, err return KeptTaken{}, err
} }
key := ReservedKey(module, series) key := ReservedKey(module, series)
for { for {
cur, rev, found, err := r.get(ctx, key) cur, rev, found, err := r.get(ctx, key)
if err != nil || !found || cur.Version != version || cur.BuiltAt.IsZero() || len(cur.Kept) == 0 { if err != nil || !found || cur.Version != version || cur.BuiltAt.IsZero() {
return nil, nil, err return KeptTaken{}, err
}
if len(cur.Kept) == 0 {
return KeptTaken{Reserved: cur, Standing: true}, nil
} }
var arts []string var arts []string
var unmatched []KeptPublished var unmatched []KeptPublished
@@ -959,13 +962,13 @@ func (r *Reserver) Kept(ctx context.Context, module, version string) ([]Marked,
if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) { if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) {
continue continue
} else if err != nil { } else if err != nil {
return nil, nil, fmt.Errorf("%s cannot be written: %w", key, err) return KeptTaken{}, fmt.Errorf("%s cannot be written: %w", key, err)
} }
var marked []Marked took := KeptTaken{Reserved: cur, Standing: true, Unmatched: unmatched}
for _, a := range arts { for _, a := range arts {
marked = append(marked, Marked{Reserved: cur, Artifact: a}) took.Marked = append(took.Marked, Marked{Reserved: cur, Artifact: a})
} }
return marked, unmatched, nil return took, nil
} }
} }
@@ -1134,11 +1137,11 @@ const (
ReservedVerb = meshbuilds.VerbReserved ReservedVerb = meshbuilds.VerbReserved
) )
// Missing are the artifacts of v no registry seat said published, sorted. // Missing are the artifacts of v no registry seat said published, sorted; an upstream one is never awaited (H-A-486).
func (v ReservedVersion) Missing() []string { func (v ReservedVersion) Missing() []string {
var out []string var out []string
for a := range v.Artifacts { for a := range v.Artifacts {
if !v.Published[a] { if !v.Published[a] && !slices.Contains(v.Upstream, a) {
out = append(out, a) out = append(out, a)
} }
} }
@@ -5,11 +5,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"reflect" "reflect"
"strings"
"testing" "testing"
"time" "time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
) )
@@ -35,27 +33,16 @@ func (m *reserveMem) Update(ctx context.Context, key string, value []byte, rev u
} }
// TestReservation: design 47 G §369 (test 102): two builds close together reserve two versions, the key goes on // TestReservation: design 47 G §369 (test 102): two builds close together reserve two versions, the key goes on
// version-released, a built reservation with an artifact unpublished past the bound is unreleased, and nothing is reserved // version-released, a built reservation with an artifact unpublished past the bound is unreleased.
// before versions-filled.
func TestReservation(t *testing.T) { func TestReservation(t *testing.T) {
ctx := context.Background() ctx := context.Background()
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
released := []string{"0.1.18", "0.1.19", "0.2.7"} released := []string{"0.1.18", "0.1.19", "0.2.7"}
filled := true
store := &reserveMem{mem: newMem()} store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Filled: func() bool { return filled }, Now: func() time.Time { return now }, r := &Reserver{Store: store, Now: func() time.Time { return now },
ReleasedOf: func(context.Context, string) ([]string, error) { return released, nil }} ReleasedOf: func(context.Context, string) ([]string, error) { return released, nil }}
arts := []string{"m:a", "m:b"} arts := []string{"m:a", "m:b"}
filled = false
if _, err := r.Reserve(ctx, "m", "0.1", arts, Source{}); !errors.Is(err, ErrNotFilled) {
t.Fatalf("before versions-filled: %v, want ErrNotFilled", err)
}
if got, _ := r.All(ctx); len(got) != 0 {
t.Fatalf("a reservation was written before the fill: %v", got)
}
filled = true
first, err := r.Reserve(ctx, "m", "0.1", arts, Source{}) first, err := r.Reserve(ctx, "m", "0.1", arts, Source{})
if err != nil || first.Version != "0.1.20" { if err != nil || first.Version != "0.1.20" {
t.Fatalf("first build reserves %q (%v), want 0.1.20 after the highest released 0.1.19", first.Version, err) t.Fatalf("first build reserves %q (%v), want 0.1.20 after the highest released 0.1.19", first.Version, err)
@@ -86,12 +73,10 @@ func TestReservation(t *testing.T) {
} }
// The artifacts' digests, then the bound. // The artifacts' digests, then the bound.
for _, a := range arts { if v, ok, err := r.Built(ctx, "m", "0.1.23", map[string]string{"m:a": "sha256:m:a", "m:b": "sha256:m:b"}, nil); err != nil || !ok || v.BuiltAt.IsZero() {
if ok, err := r.Built(ctx, "m", "0.1.23", a, "sha256:"+a, nil); err != nil || !ok { t.Fatalf("built %+v, %v: %v", v, ok, err)
t.Fatalf("built %s: %v %v", a, ok, err)
}
} }
if ok, _ := r.Built(ctx, "m", "0.1.22", "m:a", "x", nil); ok { if _, ok, _ := r.Built(ctx, "m", "0.1.22", map[string]string{"m:a": "x"}, nil); ok {
t.Error("a digest was written under a version a newer build superseded") t.Error("a digest was written under a version a newer build superseded")
} }
published := func(_, _, a string) bool { return a == "m:a" } published := func(_, _, a string) bool { return a == "m:a" }
@@ -132,7 +117,7 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) {
t.Fatalf("reserved %q (%v), want 1.4.3", v.Version, err) t.Fatalf("reserved %q (%v), want 1.4.3", v.Version, err)
} }
deps := []meshbuilds.Dependency{{Kind: 1, Part: "mesh-sdk:go", Version: "0.1.14", Digest: "sha256:dd"}, {Kind: 3, Part: "go-toolchain:program", Version: "go1.27", Digest: "sha256:tt"}} deps := []meshbuilds.Dependency{{Kind: 1, Part: "mesh-sdk:go", Version: "0.1.14", Digest: "sha256:dd"}, {Kind: 3, Part: "go-toolchain:program", Version: "go1.27", Digest: "sha256:tt"}}
if _, err := r.Built(ctx, "m", "1.4.3", "m:a", "sha256:aa", deps); err != nil { if _, _, err := r.Built(ctx, "m", "1.4.3", map[string]string{"m:a": "sha256:aa"}, map[string][]meshbuilds.Dependency{"m:a": deps}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
rd := Reader{ rd := Reader{
@@ -171,6 +156,21 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) {
if got := cur.Missing(); !reflect.DeepEqual(got, []string{"m:b"}) { if got := cur.Missing(); !reflect.DeepEqual(got, []string{"m:b"}) {
t.Errorf("missing = %v, want m:b", got) t.Errorf("missing = %v, want m:b", got)
} }
// H-A-486: an upstream artifact is reserved and recorded with its digest, but never awaited: once the others are published
// nothing is missing.
up, err := r.Reserve(ctx, "u", "0.1", []string{"u:server", "u:tools"}, Source{Upstream: []string{"u:server"}})
if err != nil || !reflect.DeepEqual(up.Upstream, []string{"u:server"}) {
t.Fatalf("reserved %+v (%v), want u:server kept as upstream", up, err)
}
if _, _, err := r.Built(ctx, "u", up.Version, map[string]string{"u:server": "sha256:u:server", "u:tools": "sha256:u:tools"}, nil); err != nil {
t.Fatal(err)
}
if marked, _, err := r.Published(ctx, "u-tools", up.Version, "sha256:u:tools"); err != nil || len(marked) != 1 {
t.Fatalf("the published of u:tools marked %v (%v)", marked, err)
}
if cur, _, _ := r.At(ctx, ReservedKey("u", "0.1")); len(cur.Missing()) != 0 || cur.Artifacts["u:server"] != "sha256:u:server" {
t.Errorf("missing = %v with artifacts %v, want none missing and the upstream digest kept", cur.Missing(), cur.Artifacts)
}
if key, ok := ReservedBoundOf(ReservedBoundKey("m", "1.4")); !ok || key != ReservedKey("m", "1.4") || ReservedBoundFor(key) != ReservedBoundKey("m", "1.4") { if key, ok := ReservedBoundOf(ReservedBoundKey("m", "1.4")); !ok || key != ReservedKey("m", "1.4") || ReservedBoundFor(key) != ReservedBoundKey("m", "1.4") {
t.Errorf("the bound key does not name the reservation back: %q %v", key, ok) t.Errorf("the bound key does not name the reservation back: %q %v", key, ok)
} }
@@ -181,7 +181,7 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) {
func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) { func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) {
ctx := context.Background() ctx := context.Background()
rel := &reserveMem{mem: newMem()} rel := &reserveMem{mem: newMem()}
r := &Reserver{Store: &reserveMem{mem: newMem()}, Releases: rel, ReleasedKept: 2, Filled: func() bool { return true }, r := &Reserver{Store: &reserveMem{mem: newMem()}, Releases: rel, ReleasedKept: 2,
ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }}
v, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:aa"}) v, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:aa"})
if err != nil { if err != nil {
@@ -202,6 +202,44 @@ func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) {
if all, _ := r.All(ctx); len(all) != 0 { if all, _ := r.All(ctx); len(all) != 0 {
t.Errorf("reservations left: %v", all) t.Errorf("reservations left: %v", all)
} }
// Design 47 H2 H-A-547 (3), H-A-551: an importer's version at the source revision of its key's origin is the standing
// reservation of that origin once its artifact is published, then the release recorded at that source revision.
w, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:cc", Branch: "main", Revision: 41})
if err != nil {
t.Fatal(err)
}
at := func(branch string, source int64) string {
v, found, err := r.VersionAt(ctx, "m", "a", branch, source)
if err != nil || found != (v != "") {
t.Fatalf("VersionAt %s.%d: %q %v %v", branch, source, v, found, err)
}
return v
}
if v := at("main", 41); v != "" {
t.Errorf("a reservation not yet published answers %q, want none", v)
}
if _, _, err := r.Built(ctx, "m", w.Version, map[string]string{"m:a": "sha256:cc"}, nil); err != nil {
t.Fatal(err)
}
if _, _, err := r.Published(ctx, "m/a", w.Version, "sha256:cc"); err != nil {
t.Fatal(err)
}
if v := at("main", 41); v != w.Version {
t.Errorf("the published reservation at main.41 answers %q, want %s", v, w.Version)
}
if v, v2 := at("main", 40), at("feat", 41); v != "" || v2 != "" {
t.Errorf("another source revision or branch answers %q %q, want none", v, v2)
}
if _, err := r.Released(ctx, "m", w.Version); err != nil {
t.Fatal(err)
}
if v := at("main", 41); v != w.Version {
t.Errorf("once released, main.41 answers %q, want %s from the release's record", v, w.Version)
}
// H-A-558 (2): the record keeps the origin's branch with its source revision, so another branch's equal number never meets it.
if v := at("feat", 41); v != "" {
t.Errorf("once released, feat.41 answers %q, want none", v)
}
// One key per module holds the last releases, the oldest dropped (A-456b). // One key per module holds the last releases, the oldest dropped (A-456b).
for _, fp := range []string{"src2:b1", "src2:b2"} { for _, fp := range []string{"src2:b1", "src2:b2"} {
n, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp}) n, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp})
@@ -230,13 +268,13 @@ func TestPublishedAnswersByTheBuildFingerprint(t *testing.T) {
ctx := context.Background() ctx := context.Background()
heard := time.Date(2026, 11, 21, 19, 0, 0, 0, time.UTC) heard := time.Date(2026, 11, 21, 19, 0, 0, 0, time.UTC)
store := &reserveMem{mem: newMem()} store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()}, ReleasedKept: 2, Filled: func() bool { return true }, r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()}, ReleasedKept: 2,
ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }, Now: func() time.Time { return heard }} ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }, Now: func() time.Time { return heard }}
v, err := r.Reserve(ctx, "mesh-grants", "0.1", []string{"mesh-grants:busgrants", "mesh-grants:grantsstate"}, Source{Fingerprint: "src2:aa"}) v, err := r.Reserve(ctx, "mesh-grants", "0.1", []string{"mesh-grants:busgrants", "mesh-grants:grantsstate"}, Source{Fingerprint: "src2:aa"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := r.Built(ctx, "mesh-grants", v.Version, "mesh-grants:busgrants", "sha256:bb", nil); err != nil { if _, _, err := r.Built(ctx, "mesh-grants", v.Version, map[string]string{"mesh-grants:busgrants": "sha256:bb"}, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
ask := func(artifact, fp string) meshbuilds.PublishedAnswer { ask := func(artifact, fp string) meshbuilds.PublishedAnswer {
@@ -311,7 +349,7 @@ func TestTheWithdrawnVersionsAreDroppedOnceReleasedPast(t *testing.T) {
ctx := context.Background() ctx := context.Background()
store := &reserveMem{mem: newMem()} store := &reserveMem{mem: newMem()}
highest := "0.1.3" highest := "0.1.3"
r := &Reserver{Store: store, Filled: func() bool { return true }, r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()},
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{highest}, nil }} ReleasedOf: func(context.Context, string) ([]string, error) { return []string{highest}, nil }}
for _, fp := range []string{"src2:a", "src2:b", "src2:c"} { for _, fp := range []string{"src2:a", "src2:b", "src2:c"} {
if _, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp}); err != nil { if _, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp}); err != nil {
@@ -334,6 +372,27 @@ func TestTheWithdrawnVersionsAreDroppedOnceReleasedPast(t *testing.T) {
if err != nil || got.Version != "0.1.7" || len(got.Withdrawn) != 1 || got.Withdrawn["0.1.6"] != "src2:c" { if err != nil || got.Version != "0.1.7" || len(got.Withdrawn) != 1 || got.Withdrawn["0.1.6"] != "src2:c" {
t.Errorf("reserved %+v (%v); want 0.1.7 keeping only 0.1.6 withdrawn", got, err) t.Errorf("reserved %+v (%v); want 0.1.7 keeping only 0.1.6 withdrawn", got, err)
} }
// H-A-508: the release of the version that took over deletes the series key; the release record still names the
// fingerprint it withdrew, so the stale build finds the series moved, never "no version is reserved".
if _, err := r.Released(ctx, "m", "0.1.7"); err != nil {
t.Fatal(err)
}
if _, _, found, _ := r.get(ctx, ReservedKey("m", "0.1")); found {
t.Fatal("the released series key stands")
}
if by, took, err := r.TakenOver(ctx, "m", "src2:c"); err != nil || !took || by.Fingerprint != "src2:d" || by.Version != "0.1.7" {
t.Errorf("after the release taken over from src2:c by %+v (%v, %v); want src2:d 0.1.7", by, took, err)
}
if _, took, err := r.TakenOver(ctx, "m", "src2:d"); err != nil || took {
t.Errorf("the released build src2:d is said taken over (%v, %v)", took, err)
}
// A release record that cannot be read answers its error, never "not taken over".
if _, err := r.Releases.Create(ctx, ReleasedKey("n"), []byte("{not json")); err != nil {
t.Fatal(err)
}
if _, took, err := r.TakenOver(ctx, "n", "src2:x"); err == nil || took {
t.Errorf("an unreadable release record answered taken over %v, %v; want its error", took, err)
}
} }
// TestARebuildReservesAboveTheCatalogsHighestWhateverItsStandingNumberWas: design 47 G A-490b as H-A-225 amends it — a build again // TestARebuildReservesAboveTheCatalogsHighestWhateverItsStandingNumberWas: design 47 G A-490b as H-A-225 amends it — a build again
@@ -354,7 +413,7 @@ func TestARebuildReservesAboveTheCatalogsHighestWhateverItsStandingNumberWas(t *
} { } {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
store := &reserveMem{mem: newMem()} store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Filled: func() bool { return true }, r := &Reserver{Store: store,
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }} ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }}
raw, _ := json.Marshal(ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: c.standing, Fingerprint: c.standingFp, Artifacts: map[string]string{"m:a": "d"}}) raw, _ := json.Marshal(ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: c.standing, Fingerprint: c.standingFp, Artifacts: map[string]string{"m:a": "d"}})
if _, err := store.Create(ctx, ReservedKey("m", "0.1"), raw); err != nil { if _, err := store.Create(ctx, ReservedKey("m", "0.1"), raw); err != nil {
@@ -399,13 +458,13 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) {
return held, readErr return held, readErr
}, },
HeldElsewhere: func(_ context.Context, _ string, s []string) { skipped = append(skipped, s...) }} HeldElsewhere: func(_ context.Context, _ string, s []string) { skipped = append(skipped, s...) }}
v, err := r.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, Source{Fingerprint: "fp1", GoPackage: true}) v, err := r.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, Source{Fingerprint: "fp1", Repository: "o/r", Commit: "c1"})
if err != nil || v.Version != "0.1.39" || len(skipped) != 2 { if err != nil || v.Version != "0.1.39" || len(skipped) != 2 {
t.Fatalf("reserved %q (%v), skipped %v: want 0.1.39 past the two numbers the registry holds", v.Version, err, skipped) t.Fatalf("reserved %q (%v), skipped %v: want 0.1.39 past the two numbers the registry holds", v.Version, err, skipped)
} }
// The build ends; the registry holds 0.1.39 at another digest meanwhile: the number is withdrawn, and the build again of the same // The build ends; the registry holds 0.1.39 at another digest meanwhile: the number is withdrawn, and the build again of the same
// fingerprint reserves the next number no registry holds, with no digest yet (H-A-279). // fingerprint reserves the next number no registry holds, with no digest yet (H-A-279).
if _, err := r.Built(ctx, "node-tools", "0.1.39", "node-tools:program", "sha256:7c9b10", nil); err != nil { if _, _, err := r.Built(ctx, "node-tools", "0.1.39", map[string]string{"node-tools:program": "sha256:7c9b10"}, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if w, ok, err := r.Withdraw(ctx, "node-tools", "0.1.39"); err != nil || !ok || w.Withdrawn["0.1.39"] != "fp1" { if w, ok, err := r.Withdraw(ctx, "node-tools", "0.1.39"); err != nil || !ok || w.Withdrawn["0.1.39"] != "fp1" {
@@ -413,9 +472,9 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) {
} }
held = []string{"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.2.0"} held = []string{"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.2.0"}
// The build again of a done key reserves as a rebuild (A-490b): a withdrawn number is never its floor's to reuse. // The build again of a done key reserves as a rebuild (A-490b): a withdrawn number is never its floor's to reuse.
again, err := r.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, Source{Fingerprint: "fp1", GoPackage: true, Rebuild: true}) again, err := r.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, Source{Fingerprint: "fp1", Repository: "o/r", Commit: "c1", Rebuild: true})
if err != nil || again.Version != "0.1.41" || again.Artifacts["node-tools:program"] != "" || again.Withdrawn["0.1.39"] != "fp1" || again.Tag != "" { if err != nil || again.Version != "0.1.41" || again.Artifacts["node-tools:program"] != "" || again.Withdrawn["0.1.39"] != "fp1" || again.Tag != "" {
t.Fatalf("the build again reserved %+v (%v), want 0.1.41 with no digest, 0.1.39 kept withdrawn, and no tag (no Go package name known)", again, err) t.Fatalf("the build again reserved %+v (%v), want 0.1.41 with no digest, 0.1.39 kept withdrawn, and no tag (design 47 H2 H-A-494)", again, err)
} }
if at, _ := r.AtVersion(ctx, "0.1.39"); len(at) != 0 { if at, _ := r.AtVersion(ctx, "0.1.39"); len(at) != 0 {
t.Errorf("the index by version still names the withdrawn number: %v", at) t.Errorf("the index by version still names the withdrawn number: %v", at)
@@ -428,50 +487,4 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) {
if v, err := r.Reserve(ctx, "node-tools", "0.2", []string{"node-tools:program"}, Source{Fingerprint: "fp1"}); err != nil || v.Version != "0.2.1" { if v, err := r.Reserve(ctx, "node-tools", "0.2", []string{"node-tools:program"}, Source{Fingerprint: "fp1"}); err != nil || v.Version != "0.2.1" {
t.Errorf("with the registry down reserved %q (%v), want 0.2.1 (what it answered still skipped)", v.Version, err) t.Errorf("with the registry down reserved %q (%v), want 0.2.1 (what it answered still skipped)", v.Version, err)
} }
// Design 47 H2 §796: a Go package's tags are read before it reserves, once per catalog revision; a number whose tag
// `<directory>/v<version>` stands at another commit is skipped and said, one at the build's own commit is not; the version's
// tag names the Go module's directory; a read met away lets the reservation go on, any other failure refuses it.
r.HeldNumbers = nil
var tagReads int
var tagsErr error
var tagsAway bool
var elsewhere []string
tags := []git.Tag{{Tag: "modules/nt/v0.3.0", Commit: "c-other"}, {Tag: "modules/nt/v0.3.1", Commit: "c-mine"}, {Tag: "modules/nt/v0.3.2", Commit: "c-other2"}}
r.Names = func(_ context.Context, module, artifact string) (string, bool, error) {
return "git.example/o/r/modules/nt", module == "node-tools" && artifact == "lib", nil
}
r.Tags = func(_ context.Context, repository, prefix string) ([]git.Tag, bool, error) {
tagReads++
if repository != "o/r" || prefix != "modules/nt/v0.3." {
t.Errorf("tags read of %s %q, want o/r modules/nt/v0.3.", repository, prefix)
}
return tags, tagsAway, tagsErr
}
r.TaggedElsewhere = func(_ context.Context, _ string, s []string) { elsewhere = append(elsewhere, s...) }
at := Source{Fingerprint: "fp3", GoPackage: true, GoArtifact: "lib", Repository: "o/r", Commit: "c-mine", Branch: "main", CatalogRevision: 7}
v3, err := r.Reserve(ctx, "node-tools", "0.3", []string{"node-tools:lib"}, at)
if err != nil || v3.Version != "0.3.1" || v3.Tag != "modules/nt/v0.3.1" || len(elsewhere) != 1 || !strings.Contains(elsewhere[0], "0.3.0") {
t.Fatalf("reserved %+v (%v), tagged elsewhere %v: want 0.3.1 (0.3.0 tagged at another commit, 0.3.1 at the build's own), tag modules/nt/v0.3.1", v3, err, elsewhere)
}
at.Fingerprint, at.Commit, elsewhere = "fp4", "c-new", nil
if v4, err := r.Reserve(ctx, "node-tools", "0.3", []string{"node-tools:lib"}, at); err != nil || v4.Version != "0.3.3" || tagReads != 1 || len(elsewhere) != 1 || !strings.Contains(elsewhere[0], "0.3.2") {
t.Fatalf("reserved %+v (%v) after %d reads, tagged elsewhere %v: want 0.3.3 past 0.3.2's tag, the tags read once for revision main.7", v4, err, tagReads, elsewhere)
}
at.CatalogRevision, at.Fingerprint, tagsErr, tagsAway = 8, "fp5", errors.New("the forge is away"), true
if v5, err := r.Reserve(ctx, "node-tools", "0.3", []string{"node-tools:lib"}, at); err != nil || v5.Version != "0.3.4" || tagReads != 2 {
t.Fatalf("with the tags away reserved %+v (%v) after %d reads, want 0.3.4 and the reservation going on", v5, err, tagReads)
}
at.CatalogRevision, at.Fingerprint, tagsAway = 9, "fp6", false
if _, err := r.Reserve(ctx, "node-tools", "0.3", []string{"node-tools:lib"}, at); err == nil || !strings.Contains(err.Error(), "tags") {
t.Errorf("a tags read refused not away reserved anyway (%v), want the reservation refused naming the tags", err)
}
if d, ok := GoDirectory("git.example/novox/mesh-sdk/go", "https://git.example/novox/mesh-sdk.git"); !ok || d != "go" || GoTagOf(d, "0.1.9") != "go/v0.1.9" {
t.Errorf("mesh-sdk's Go package: directory %q (%v), want go and the tag go/v0.1.9", d, ok)
}
if d, ok := GoDirectory("git.example/o/r", "o/r"); !ok || d != "" || GoTagOf(d, "1.0.0") != "v1.0.0" {
t.Errorf("a root Go module: directory %q (%v), want the root and the tag v1.0.0", d, ok)
}
if _, ok := GoDirectory("git.example/o/rr/x", "o/r"); ok {
t.Error("a module path of another repository was given a directory")
}
} }
@@ -12,17 +12,20 @@ import (
) )
// TestReservedByNameAnswersFromTheViewAndTheCatalog: design 47 G §572, §582, A-70 — a package's name (an npm name or a Go // TestReservedByNameAnswersFromTheViewAndTheCatalog: design 47 G §572, §582, A-70 — a package's name (an npm name or a Go
// module path) is mapped to its module from the catalog half's view; the reserved version answers as for the module, a version // module path) is mapped to its module from the catalog half's entries (design 47 G §348); the reserved version answers as for the module, a version
// no reservation holds is asked of the catalog's versions and answers released with the release's digests, and a name no entry // no reservation holds is asked of the catalog's versions and answers released with the release's digests, and a name no entry
// carries, one more than one carries, or a version neither reserved nor released answers error, set alone. // carries, one more than one carries, or a version neither reserved nor released answers error, set alone.
func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) { func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
ctx := context.Background() ctx := context.Background()
view := packagesMem{ pkg := func(ref, name string) meshcatalog.Artifact {
"git=2enovox=2ebe/novox/mesh-sdk/go.0.1": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.1"}`), return meshcatalog.Artifact{Ref: ref, Kind: KindPackage, Package: &meshcatalog.ArtifactPackage{Name: name}}
"git=2enovox=2ebe/novox/mesh-sdk/go.0.2": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.2"}`), }
"@novox/mesh-sdk.0.1": []byte(`{"v":1,"name":"@novox/mesh-sdk","package":"mesh-sdk/ts","series":"0.1"}`), entries := func() []meshcatalog.CatalogEntry {
"twice.0.1": []byte(`{"v":1,"name":"twice","package":"a/x","series":"0.1"}`), return []meshcatalog.CatalogEntry{
"twice-b.0.1": []byte(`{"v":1,"name":"twice","package":"b/y","series":"0.1"}`), {Module: "mesh-sdk", Artifacts: []meshcatalog.Artifact{pkg("mesh-sdk:go", "git.novox.be/novox/mesh-sdk/go"), pkg("mesh-sdk:ts", "@novox/mesh-sdk")}},
{Module: "a", Artifacts: []meshcatalog.Artifact{pkg("a:x", "twice")}},
{Module: "b", Artifacts: []meshcatalog.Artifact{pkg("b:y", "twice")}},
}
} }
store := &reserveMem{mem: newMem()} store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.3"}, nil }} r := &Reserver{Store: store, ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.3"}, nil }}
@@ -40,7 +43,7 @@ func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
asked = append(asked, module) asked = append(asked, module)
return []meshcatalog.VersionEntry{{Module: module, Version: "0.1.2", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "mesh-sdk:go", Digest: "sha256:dd"}}}}, nil return []meshcatalog.VersionEntry{{Module: module, Version: "0.1.2", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "mesh-sdk:go", Digest: "sha256:dd"}}}}, nil
} }
carriers := Carriers(view) carriers := CarriersFrom(entries)
ask := func(name, version string) meshbuilds.ReservedAnswer { ask := func(name, version string) meshbuilds.ReservedAnswer {
t.Helper() t.Helper()
got, err := AnswerReservedByName(ctx, rd, carriers, released, name, version) got, err := AnswerReservedByName(ctx, rd, carriers, released, name, version)
@@ -81,7 +84,8 @@ func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
if got := ask("@novox/mesh-sdk", "9.9.9"); !strings.Contains(got.Error, "reserved or released") { if got := ask("@novox/mesh-sdk", "9.9.9"); !strings.Contains(got.Error, "reserved or released") {
t.Errorf("a version never reserved = %+v, want refused as neither reserved nor released", got) t.Errorf("a version never reserved = %+v, want refused as neither reserved nor released", got)
} }
if _, err := AnswerReservedByName(ctx, rd, Carriers(packagesMem(nil)), released, "x", ""); err == nil { unreadable := func(context.Context, string) ([]Built, error) { return nil, errors.New("down") }
if _, err := AnswerReservedByName(ctx, rd, unreadable, released, "x", ""); err == nil {
t.Error("an unreadable view was answered as if no entry carried the name") t.Error("an unreadable view was answered as if no entry carried the name")
} }
if _, err := AnswerReservedByName(ctx, rd, carriers, func(context.Context, string) ([]meshcatalog.VersionEntry, error) { return nil, errors.New("down") }, "git.novox.be/novox/mesh-sdk/go", "0.1.2"); err == nil { if _, err := AnswerReservedByName(ctx, rd, carriers, func(context.Context, string) ([]meshcatalog.VersionEntry, error) { return nil, errors.New("down") }, "git.novox.be/novox/mesh-sdk/go", "0.1.2"); err == nil {
@@ -3,9 +3,7 @@ package versions
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"strings" "strings"
"time"
) )
// AllFilter is the key filter of every version of every name: two tokens. // AllFilter is the key filter of every version of every name: two tokens.
@@ -37,191 +35,3 @@ type Store interface {
// KeysOf are the keys under a filter (NameFilter, or AllFilter for every key). // KeysOf are the keys under a filter (NameFilter, or AllFilter for every key).
KeysOf(ctx context.Context, filter string) ([]string, error) KeysOf(ctx context.Context, filter string) ([]string, error)
} }
// Versions is the builder's state.
type Versions struct {
Store Store
Now func() time.Time
}
// Of is every entry of name.
func (v Versions) Of(ctx context.Context, name string) ([]Entry, error) {
keys, err := v.Store.KeysOf(ctx, NameFilter(name))
if err != nil {
return nil, fmt.Errorf("the versions of %s cannot be listed: %w", name, err)
}
var out []Entry
for _, k := range keys {
raw, _, found, err := v.Store.Get(ctx, k)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
if !found {
continue
}
e, err := Decode(raw)
if err != nil {
return nil, fmt.Errorf("%s holds what is not a version: %w", k, err)
}
out = append(out, e)
}
return InOrder(out), nil
}
// Claim is one numbering asked of the builder.
type Claim struct {
Name, Kind, Series, Module, Fingerprint, Commit, Revision, Digest, Seat string
Merge uint64
Floor Floor
// Fresh numbers anew a fingerprint or revision already numbered: builder_publish_again after a published (design 51
// *Tools of the builder*).
Fresh bool
}
// Number numbers a claim under compare-and-set: two claims of one name never get one number, the second reading the
// first's key and taking the next (ADR 0606 §2). It answers the decision and, when it numbered or kept a version, its
// entry. Attempts are bounded by the claims the name can meet at once; a store that keeps conflicting is an error.
func (v Versions) Number(ctx context.Context, c Claim) (Decision, Entry, error) {
if c.Series == "" {
c.Series = DefaultSeries
}
for attempt := 0; attempt < 16; attempt++ {
entries, err := v.Of(ctx, c.Name)
if err != nil {
return Decision{}, Entry{}, err
}
d := Decide(fresh(entries, c), c.Kind, c.Series, c.Fingerprint, c.Revision, c.Floor)
if d.Version == "" {
return d, Entry{}, nil
}
if d.Keep {
for _, e := range entries {
if e.Version == d.Version {
return d, e, nil
}
}
}
e := Entry{Name: c.Name, Kind: c.Kind, Series: c.Series, Version: d.Version, Module: c.Module,
Fingerprint: c.Fingerprint, Commit: c.Commit, Revision: c.Revision, Digest: c.Digest, Seat: c.Seat,
State: Numbered, At: v.now(), Merge: c.Merge}
raw, err := Encode(e)
if err != nil {
return Decision{}, Entry{}, err
}
_, err = v.Store.Create(ctx, Key(c.Name, d.Version), raw)
if errors.Is(err, ErrConflict) {
continue // another claim took this number: read again and take the next
}
if err != nil {
return Decision{}, Entry{}, fmt.Errorf("%s@%s: %w", c.Name, d.Version, err)
}
return d, e, nil
}
return Decision{}, Entry{}, fmt.Errorf("%s: the versions kept changing under 16 claims", c.Name)
}
// ErrNotNumbered is a version the state versions does not hold (design 51's numbering by name): a version the reservation
// numbered (§369) is never held there.
var ErrNotNumbered = errors.New("not numbered by the builder")
// Mark moves one version to a new state by compare-and-set, as the holders' events say (published, refused, removed):
// change edits the entry read; a version the state does not hold is an error naming it.
func (v Versions) Mark(ctx context.Context, name, version string, change func(*Entry)) (Entry, error) {
key := Key(name, version)
for attempt := 0; attempt < 16; attempt++ {
raw, rev, found, err := v.Store.Get(ctx, key)
if err != nil {
return Entry{}, fmt.Errorf("%s: %w", key, err)
}
if !found {
return Entry{}, fmt.Errorf("%s@%s is %w", name, version, ErrNotNumbered)
}
e, err := Decode(raw)
if err != nil {
return Entry{}, fmt.Errorf("%s holds what is not a version: %w", key, err)
}
change(&e)
e.At = v.now()
out, err := Encode(e)
if err != nil {
return Entry{}, err
}
if _, err := v.Store.Update(ctx, key, out, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return Entry{}, fmt.Errorf("%s: %w", key, err)
}
return e, nil
}
return Entry{}, fmt.Errorf("%s@%s kept changing under 16 marks", name, version)
}
// Recorded is the holder's question through builder_versions (ADR 0605 §4): whether name, version and digest are a
// version the builder numbered. It answers the entry when they are, and why not otherwise.
func (v Versions) Recorded(ctx context.Context, name, version, digest string) (Entry, bool, string, error) {
raw, _, found, err := v.Store.Get(ctx, Key(name, version))
if err != nil {
return Entry{}, false, "", err
}
if !found {
return Entry{}, false, fmt.Sprintf("%s@%s is not a version the builder numbered", name, version), nil
}
e, err := Decode(raw)
if err != nil {
return Entry{}, false, "", err
}
switch {
case e.State == Removed:
return e, false, fmt.Sprintf("%s@%s was removed (%s)", name, version, e.Reason), nil
case e.Digest != "" && digest != "" && e.Digest != digest:
return e, false, fmt.Sprintf("%s@%s is recorded with digest %s, not %s", name, version, e.Digest, digest), nil
}
return e, true, "", nil
}
func (v Versions) now() time.Time {
if v.Now != nil {
return v.Now().UTC()
}
return time.Now().UTC()
}
// fresh is entries as Decide reads them for c: with Fresh, the entries of c's fingerprint and revision still count for the
// next number but keep none.
func fresh(entries []Entry, c Claim) []Entry {
if !c.Fresh {
return entries
}
out := make([]Entry, len(entries))
for i, e := range entries {
if e.Tag == "" && (e.Fingerprint == c.Fingerprint || (c.Revision != "" && e.Revision == c.Revision)) {
e.Fingerprint, e.Revision = "", ""
}
out[i] = e
}
return out
}
// All is every entry of every name, by name in order: what the versions' readers read.
func (v Versions) All(ctx context.Context) ([]Entry, error) {
keys, err := v.Store.KeysOf(ctx, AllFilter)
if err != nil {
return nil, fmt.Errorf("the versions cannot be listed: %w", err)
}
var out []Entry
for _, k := range keys {
raw, _, found, err := v.Store.Get(ctx, k)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
if !found {
continue
}
e, err := Decode(raw)
if err != nil {
return nil, fmt.Errorf("%s holds what is not a version: %w", k, err)
}
out = append(out, e)
}
return out, nil
}
@@ -1,31 +0,0 @@
package versions
import (
"strings"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
)
// GoTagOf is the git tag a Go package's released version is written as (design 47 H2 §796): `<directory>/v<version>`, the
// directory of its Go module in the repository, which the Go toolchain's direct fallback reads; `v<version>` at the root. The
// `go/v<version>` tags go from new versions.
func GoTagOf(directory, version string) string { return TagPrefix(directory) + version }
// GoDirectory is the directory of the Go module path modulePath in repository (`<owner>/<name>`, or a clone address naming
// it): the part of the path after the repository's own, as the Go toolchain reads a module kept in a subdirectory; empty at
// the root. ok is false when the path is not one of that repository.
func GoDirectory(modulePath, repository string) (string, bool) {
repo := "/" + strings.ToLower(trunk.RepositoryName(repository))
lower := strings.ToLower(modulePath)
for from := 0; ; {
i := strings.Index(lower[from:], repo)
if i < 0 || repo == "/" {
return "", false
}
end := from + i + len(repo)
if end == len(lower) || lower[end] == '/' {
return strings.Trim(modulePath[end:], "/"), true
}
from = end
}
}
@@ -14,7 +14,6 @@ import (
const ( const (
VersionsTool = "builder_versions" VersionsTool = "builder_versions"
PublishAgainTool = "builder_publish_again" PublishAgainTool = "builder_publish_again"
FloorAgainTool = "builder_floor_again"
OldFormTool = "builder_old_form" OldFormTool = "builder_old_form"
// OldFormClosedEvent is the builder's own family `version`, kept seven days, // OldFormClosedEvent is the builder's own family `version`, kept seven days,
// apart from its builds' ends, so a waiter on a build's end does not wake on them. // apart from its builds' ends, so a waiter on a build's end does not wake on them.
@@ -76,10 +75,77 @@ func (r Reader) values(state string) (map[string]json.RawMessage, *StateCapped,
return out, nil, nil return out, nil, nil
} }
// readStore is a Store over a Reader that refuses every write: the tools bundle only reads versions. // VersionsAnswer is what builder_versions answers, from the reservations alone (design 47 H §756, G §372, §381): what the
// seat mesh-builds' verb reserved answers for the name, and, asked for a version and a digest, whether the reservation holds
// that version with that digest.
type VersionsAnswer struct {
Name string `json:"name"`
// Asked, Recorded and Why answer a holder's question for one version and digest (ADR 0605 §4).
Asked string `json:"asked,omitempty"`
Recorded *bool `json:"recorded,omitempty"`
Why string `json:"why,omitempty"`
// Reserved is what the seat mesh-builds' verb reserved answers for the name (and version): the reserved or released version
// with each artifact's digest, or its error (design 47 G §572, §582).
Reserved *meshbuilds.ReservedAnswer `json:"reserved,omitempty"`
}
// AnswerVersions is builder_versions: what the reservation answers for a name, read through reserve (the seat mesh-builds'
// verb reserved); with a version and a digest, recorded says whether that version is the one reserved or released and an
// artifact of it has that digest or none recorded yet, the question a registry seat's holder asks before it stores
// (ADR 0605 §4, design 47 G §381, A-490j).
func AnswerVersions(name, version, digest string, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) (VersionsAnswer, error) {
name, version, digest = strings.TrimSpace(name), strings.TrimSpace(version), strings.TrimSpace(digest)
if name == "" {
return VersionsAnswer{}, errors.New("name is required: the package, image, bundle or archive name")
}
if reserve == nil {
return VersionsAnswer{}, errors.New("the seat mesh-builds' reserved cannot be asked")
}
ra, err := reserve(name, version)
if err != nil {
return VersionsAnswer{}, fmt.Errorf("the seat mesh-builds' reserved did not answer for %s: %w", name, err)
}
out := VersionsAnswer{Name: name, Reserved: &ra}
if version == "" {
return out, nil
}
ok, why := recordedIn(ra, name, version, digest)
out.Asked, out.Recorded, out.Why = version, &ok, why
return out, nil
}
// recordedIn is whether the reservation answer ra holds name@version with digest, and why not.
func recordedIn(ra meshbuilds.ReservedAnswer, name, version, digest string) (bool, string) {
switch {
case ra.Error != "":
return false, ra.Error
case ra.Version != version:
return false, fmt.Sprintf("%s has no reservation of version %s of %s (it holds %s)", ra.Module, version, name, ra.Version)
}
var held []string
for _, a := range ra.Artifacts {
if a.Digest == digest || a.Digest == "" {
return true, ""
}
held = append(held, a.Digest)
}
if len(held) == 0 {
return false, fmt.Sprintf("%s holds %s@%s with no artifact, so no digest takes %s", ra.Module, name, version, digest)
}
return false, fmt.Sprintf("%s holds %s@%s for digest %s, not %s", ra.Module, name, version, strings.Join(held, ", "), digest)
}
// VersionsDescription is builder_versions' description.
const VersionsDescription = "A name's reservation, from the reservations alone (the numbering from before G is gone, design 47 H §756): " +
"what the seat mesh-builds' verb reserved answers for the package, image, bundle or archive name, the reserved or released version " +
"with each artifact's digest. With version, and digest, it also answers recorded: whether that version is the one reserved or " +
"released and an artifact of it has that digest (or none recorded yet), and why not: the question a registry seat's holder asks " +
"before it stores a publish (ADR 0605 §4). Read-only."
// readStore is a Store over a Reader that refuses every write: the tools bundle only reads the builder's states.
type readStore struct{ r Reader } type readStore struct{ r Reader }
var errReadOnly = errors.New("the versions are written by the builder alone") var errReadOnly = errors.New("the builder's states are written by the builder alone")
func (s readStore) Get(_ context.Context, key string) ([]byte, uint64, bool, error) { func (s readStore) Get(_ context.Context, key string) ([]byte, uint64, bool, error) {
v, ok, err := s.r.Get(key) v, ok, err := s.r.Get(key)
@@ -102,49 +168,3 @@ func (s readStore) KeysOf(_ context.Context, filter string) ([]string, error) {
} }
return out, nil return out, nil
} }
// VersionsAnswer is what builder_versions answers.
type VersionsAnswer struct {
Name string `json:"name"`
Versions []Entry `json:"versions"`
// Asked, Recorded and Why answer a holder's question for one version and digest (ADR 0605 §4).
Asked string `json:"asked,omitempty"`
Recorded *bool `json:"recorded,omitempty"`
Why string `json:"why,omitempty"`
// Reserved is what the seat mesh-builds' verb reserved answers for the name (and version): the reserved or released version
// with each artifact's digest, or its error (design 47 G §572, §582).
Reserved *meshbuilds.ReservedAnswer `json:"reserved,omitempty"`
}
// AnswerVersions is builder_versions: a name's versions in order, in one call; with a version (and a digest), whether
// the builder numbered it with that digest, which the holder asks before it stores (ADR 0605 §4).
func AnswerVersions(ctx context.Context, r Reader, name, version, digest string) (VersionsAnswer, error) {
name = strings.TrimSpace(name)
if name == "" {
return VersionsAnswer{}, errors.New("name is required: the package, image, bundle or archive name")
}
v := Versions{Store: readStore{r}}
all, err := v.Of(ctx, name)
if err != nil {
return VersionsAnswer{}, err
}
out := VersionsAnswer{Name: name, Versions: all}
if out.Versions == nil {
out.Versions = []Entry{}
}
if version = strings.TrimSpace(version); version != "" {
_, ok, why, err := v.Recorded(ctx, name, version, strings.TrimSpace(digest))
if err != nil {
return VersionsAnswer{}, fmt.Errorf("%s@%s: %w", name, version, err)
}
out.Asked, out.Recorded, out.Why = version, &ok, why
}
return out, nil
}
// VersionsDescription is builder_versions' description.
const VersionsDescription = "A name's versions as the builder numbered them (its state versions, design 51): every trunk and tagged " +
"version of a package, image, bundle or archive in order, each with its kind, series, fingerprint, commit, source revision, digest, " +
"seat, state (numbered, published, refused with its reason, removed with its time, reason and the event that removed it, or kept: its seat kept it whole on remove, its digest shared, with the reason and the other tags naming it, kept_with) and when. " +
"With version, and digest, it also answers recorded: whether the builder numbered that version with that digest, and why not: the " +
"question a registry seat's holder asks before it stores a publish (ADR 0605 §4). Read-only."
@@ -1,46 +1,19 @@
// Package versions is the builder's state `versions` (novox/hq design 51 *The versions*, ADR 0606): one key per name, // Package versions holds the builder's versions as the reservation numbers them (novox/hq design 47 G §369): the state
// tag and version, written only by the builder under compare-and-set, read by others only through the builder's tool // reserved, its index and releases, the publish queue, the old form's window and the builder's bounds. The state versions
// builder_versions or its events (ADR 0596 §2). It holds what each version is (its fingerprint, commit, source revision // numbered before G goes with its numbering (design 47 H §756); builder_versions answers from the reservations alone.
// and digest) and where it stands: numbered, published, refused with its reason, or removed with its time, reason and the
// event that removed it.
//
// The state is declared in the builder's old `state` section (ADR 0619: the builder is one of the foundation's nine
// parts), history one; its cap is 64 MiB, the most the template state allows (ADR 0595 §3), and past 80 % of it the
// builder writes a finding, cleared below it (Fill).
package versions package versions
import ( import (
"encoding/json"
"errors"
"fmt" "fmt"
"sort"
"strconv" "strconv"
"strings" "strings"
"time"
) )
// State is the builder state's name; its bucket is `<module>_versions` of the credential's module.
const ( const (
State = "versions"
// Cap is the bucket's cap in bytes (64 MiB); FullPercent the share of it past which the builder writes its finding.
Cap = 64 << 20
FullPercent = 80
// DefaultSeries is the series of a name whose manifest declares none (design 32). // DefaultSeries is the series of a name whose manifest declares none (design 32).
DefaultSeries = "0.1" DefaultSeries = "0.1"
) )
// The states a version is in.
const (
Numbered = "numbered"
Published = "published"
Refused = "refused"
Removed = "removed"
// Kept is a tagged version its seat kept whole on remove: another tag names its digest, so the store cannot remove the
// tag alone (review round 2; the registry seats' `kept`). Its Reason is the seat's (shared-digest), KeptWith the
// other tags; it is asked no more.
Kept = "kept"
)
// The kinds the builder numbers: a package per source revision, the rest per fingerprint (design 51). // The kinds the builder numbers: a package per source revision, the rest per fingerprint (design 51).
const ( const (
KindPackage = "package" KindPackage = "package"
@@ -49,82 +22,8 @@ const (
KindArchive = "archive" KindArchive = "archive"
) )
// Entry is one key of the state: a version of a name, tagged or not. // Key is a key of two tokens, a name and a version (or series) each escaped (EscapeToken), so a name's keys are the keys
type Entry struct { // under NameFilter and no name's keys fall under another's.
Name string `json:"name"`
Kind string `json:"kind"`
Series string `json:"series"`
Version string `json:"version"`
// Tag is the cleaned tag of a tagged version (`feat-x`); empty for a trunk version.
Tag string `json:"tag,omitempty"`
Module string `json:"module"`
Fingerprint string `json:"fingerprint"`
Commit string `json:"commit,omitempty"`
// Revision is the source revision a package's version is numbered for (one version per revision, design 51).
Revision string `json:"revision,omitempty"`
// Digest is the digest the build recorded (an image's manifest, a blob's, Go's h1: hash).
Digest string `json:"digest,omitempty"`
// Seat is the registry seat it is published to.
Seat string `json:"seat,omitempty"`
State string `json:"state"`
At time.Time `json:"at"`
// Reason is why it was refused or removed: the holder's reason, a branch's end, retention, the sweep.
Reason string `json:"reason,omitempty"`
// Repository is a tagged version's repository: its branch's end removes it (Untagged).
Repository string `json:"repository,omitempty"`
// KeptWith are the other tags naming its digest, when its seat kept it (Kept).
KeptWith []string `json:"kept_with,omitempty"`
// RemovedBy is the id of the event that removed it.
RemovedBy string `json:"removed_by,omitempty"`
// RefusedDigest is the digest the holder refused: one other than Digest means the seat was offered other bytes under
// this number, which builder_publish_again refuses to publish again (design 51 *Tools of the builder*).
RefusedDigest string `json:"refused_digest,omitempty"`
// Merge is the forge bridge's sequence of the merge that numbered it, for merge order.
Merge uint64 `json:"merge,omitempty"`
}
// Valid says what is wrong with an entry, or nil.
func (e Entry) Valid() error {
switch {
case strings.TrimSpace(e.Name) == "":
return errors.New("a version names no name")
case e.Version == "":
return fmt.Errorf("%s: a version with no version", e.Name)
}
switch e.State {
case Numbered, Published, Refused, Removed, Kept:
default:
return fmt.Errorf("%s@%s: unknown state %q", e.Name, e.Version, e.State)
}
switch e.Kind {
case KindPackage, KindImage, KindBundle, KindArchive:
default:
return fmt.Errorf("%s@%s: unknown kind %q", e.Name, e.Version, e.Kind)
}
if _, _, err := SplitSeries(e.Series); err != nil {
return fmt.Errorf("%s@%s: %w", e.Name, e.Version, err)
}
return nil
}
// Encode and Decode are the value's bytes.
func Encode(e Entry) ([]byte, error) {
if err := e.Valid(); err != nil {
return nil, err
}
return json.Marshal(e)
}
func Decode(raw []byte) (Entry, error) {
var e Entry
if err := json.Unmarshal(raw, &e); err != nil {
return Entry{}, err
}
return e, e.Valid()
}
// Key is the state's key of a name's version: two tokens, the name and the version each escaped (EscapeToken), so a
// name's versions are the keys under NameFilter and no name's keys fall under another's.
func Key(name, version string) string { return EscapeToken(name) + "." + EscapeToken(version) } func Key(name, version string) string { return EscapeToken(name) + "." + EscapeToken(version) }
// NameFilter is the key filter of every version of name. // NameFilter is the key filter of every version of name.
@@ -181,174 +80,3 @@ func Patch(series, version string) (int, bool) {
} }
return n, true return n, true
} }
// Floor is what the three sources answered for a name (design 51 *The floor*, ADR 0606 §3): the seat's versions, the
// package's git tags (the seat git's tags) and the pseudo-versions consumers require (the catalog half's
// indexer_requirements). A source not answered is listed in Silent.
type Floor struct {
Seat []string `json:"seat,omitempty"`
Tags []string `json:"tags,omitempty"`
Requirements []string `json:"requirements,omitempty"`
// Silent names the sources that did not answer: "seat", "git.tags", "catalog.requirements".
Silent []string `json:"silent,omitempty"`
}
// The floor's sources, as Floor.Silent names them.
const (
SourceSeat = "seat"
SourceTags = "git.tags"
SourceRequirements = "catalog.requirements"
)
// Known is whether every source answered.
func (f Floor) Known() bool { return len(f.Silent) == 0 }
// Highest is the highest count of series the floor's three sources name, -1 when none names one. A pseudo-version
// (`v0.1.14-0.2026…-abc`) counts as the version below it was cut from, so its base (`0.1.13`) counts: Go orders it
// before `0.1.14`.
func (f Floor) Highest(series string) int {
high := -1
for _, list := range [][]string{f.Seat, f.Tags, f.Requirements} {
for _, v := range list {
n, ok := Patch(series, v)
if !ok {
n, ok = pseudoBase(series, v)
}
if ok && n > high {
high = n
}
}
}
return high
}
// pseudoBase is the count a Go pseudo-version stands on: `v0.1.14-0.<time>-<hash>` is cut after `v0.1.13`.
func pseudoBase(series, version string) (int, bool) {
version = strings.TrimPrefix(version, "v")
base, rest, ok := strings.Cut(version, "-")
if !ok || !strings.HasPrefix(rest, "0.") || strings.Count(rest, "-") != 1 {
return 0, false
}
n, ok := Patch(series, base)
if !ok || n == 0 {
return 0, false
}
return n - 1, true
}
// Next is the next trunk version of name in series: one above the highest of the trunk versions entries hold and the
// floor (design 51: a name with none starts at `<series>.0`).
func Next(entries []Entry, series string, floor Floor) string {
high := floor.Highest(series)
for _, e := range entries {
if e.Tag != "" || e.Series != series {
continue
}
if n, ok := Patch(series, e.Version); ok && n > high {
high = n
}
}
return fmt.Sprintf("%s.%d", series, high+1)
}
// Decision is what the builder does with a trunk build at its claim.
type Decision struct {
// Version is the version the build is published under; empty when it is built unnumbered (Unnumbered) or waits (Wait).
Version string
// Keep is true when the version is one entries already hold for this fingerprint or source revision.
Keep bool
// Publish is false only for a package's revision held published: it publishes nothing (design 51).
Publish bool
// Unnumbered: an image, bundle or archive whose floor is not known is built and published by its digest, numbered
// once the floor answers (ADR 0617 §1).
Unnumbered bool
// Wait: a package whose floor is not known waits for it (a package is published only under its version).
Wait bool
// Why is said in the build log.
Why string
}
// Decide numbers a trunk build of kind for name in series at fingerprint and source revision, from what entries hold of
// the name and what the floor answered (design 51 *The versions*, ADR 0606, ADR 0617 §1):
// - a package is numbered per source revision: a revision held published keeps its version and publishes nothing; a
// revision numbered or refused but never stored is published again under the same version;
// - an image, bundle or archive is numbered per fingerprint: a fingerprint already numbered keeps its number;
// - otherwise the next version, when the floor is known; else an image, bundle or archive is built unnumbered and a
// package waits.
func Decide(entries []Entry, kind, series, fingerprint, revision string, floor Floor) Decision {
for _, e := range latestFirst(entries) {
if e.Tag != "" || e.State == Removed {
continue
}
switch {
case kind == KindPackage && revision != "" && e.Revision == revision:
if e.State == Published {
return Decision{Version: e.Version, Keep: true, Why: fmt.Sprintf("version %s kept: source revision %s is published under it, and a package's content is its source", e.Version, revision)}
}
return Decision{Version: e.Version, Keep: true, Publish: true, Why: fmt.Sprintf("version %s kept: source revision %s was numbered %s but never stored, so it is published under it", e.Version, revision, e.State)}
case kind != KindPackage && e.Fingerprint == fingerprint:
return Decision{Version: e.Version, Keep: true, Publish: e.State != Published, Why: fmt.Sprintf("version %s kept: fingerprint %s is numbered under it", e.Version, fingerprint)}
}
}
if !floor.Known() {
silent := strings.Join(floor.Silent, ", ")
if kind == KindPackage {
return Decision{Wait: true, Why: "the package waits for its floor: " + silent + " did not answer"}
}
return Decision{Unnumbered: true, Publish: true, Why: "built unnumbered and published by its digest: the floor is not known (" + silent + " did not answer); numbered once it answers"}
}
v := Next(entries, series, floor)
return Decision{Version: v, Publish: true, Why: "numbered " + v}
}
// Fill is whether a bucket holding bytes of cap is past its finding's mark.
func Fill(bytes, capacity uint64) (share float64, full bool) {
if capacity == 0 {
return 0, false
}
share = float64(bytes) / float64(capacity)
return share, bytes*100 >= capacity*FullPercent
}
// InOrder sorts a name's entries by version, trunk versions by count and tagged ones after the trunk version they stand
// below: the order builder_versions answers.
func InOrder(entries []Entry) []Entry {
out := append([]Entry(nil), entries...)
sort.SliceStable(out, func(i, j int) bool {
ki, kj := orderKey(out[i]), orderKey(out[j])
if ki.n != kj.n {
return ki.n < kj.n
}
if ki.tagged != kj.tagged {
return ki.tagged // a tagged version stands below the trunk version of its count
}
return out[i].Version < out[j].Version
})
return out
}
type order struct {
n int
tagged bool
}
func orderKey(e Entry) order {
v := e.Version
tagged := false
if i := strings.IndexByte(v, '-'); i >= 0 {
v, tagged = v[:i], true
}
n, ok := Patch(e.Series, v)
if !ok {
n = -1
}
return order{n: n, tagged: tagged}
}
func latestFirst(entries []Entry) []Entry {
out := InOrder(entries)
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return out
}
@@ -3,16 +3,14 @@ package versions
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"maps"
"reflect" "reflect"
"slices"
"strings" "strings"
"sync" "sync"
"testing" "testing"
"time" "time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds/forms" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds/forms"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
) )
// mem is a Store in memory; before runs once before the next Create, to stage a race. // mem is a Store in memory; before runs once before the next Create, to stage a race.
@@ -75,39 +73,6 @@ func (m *mem) KeysOf(_ context.Context, filter string) ([]string, error) {
return out, nil return out, nil
} }
// keeperMem is the state floor-waits in memory.
type keeperMem map[string][]byte
func (k keeperMem) Put(key string, v []byte) error { k[key] = v; return nil }
func (k keeperMem) Delete(key string) error { delete(k, key); return nil }
func (k keeperMem) keys() ([]string, error) {
var out []string
for key := range k {
out = append(out, key)
}
return out, nil
}
func (k keeperMem) get(key string) (json.RawMessage, bool, error) { v, ok := k[key]; return v, ok, nil }
// packagesMem is the indexer's packages state as the builder reads it, in memory.
type packagesMem map[string][]byte
func (p packagesMem) Keys(context.Context) ([]string, error) {
if p == nil {
return nil, errors.New("not readable")
}
return slices.Collect(maps.Keys(p)), nil
}
func (p packagesMem) Get(_ context.Context, key string) ([]byte, bool, error) {
v, ok := p[key]
return v, ok, nil
}
func (p packagesMem) failing() packagesMem { return nil }
func known(seat, tags, reqs []string) Floor { return Floor{Seat: seat, Tags: tags, Requirements: reqs} }
// TestTheBuildersVersions holds design 51 *The versions*, *The floor* and *Tagged versions* (DLV-B1, DLV-B2, DLV-B3): // TestTheBuildersVersions holds design 51 *The versions*, *The floor* and *Tagged versions* (DLV-B1, DLV-B2, DLV-B3):
// one table per rule, the unit cases of the builder's numbering. // one table per rule, the unit cases of the builder's numbering.
func TestTheBuildersVersions(t *testing.T) { func TestTheBuildersVersions(t *testing.T) {
@@ -128,184 +93,42 @@ func TestTheBuildersVersions(t *testing.T) {
} }
} }
}) })
t.Run("floor", func(t *testing.T) { t.Run("builder_versions answers from the reservations alone", func(t *testing.T) { // B1/AC2 (DMC-5: design 47 H §756, G §372)
for _, c := range []struct { asked := ""
name string reserve := func(name, version string) (meshbuilds.ReservedAnswer, error) {
floor Floor asked = name + "@" + version
want string return meshbuilds.ReservedAnswer{Module: "m", Version: "0.1.4", Artifacts: []meshbuilds.ReservedAnswerArtifactsItem{
}{ {Artifact: "m:program", Digest: "sha256:aa"}}}, nil
{"none starts at 0", known(nil, nil, nil), "0.1.0"},
{"the Go tag of today gives v0.1.14", known(nil, []string{"go/v0.1.13"}, []string{"v0.1.14-0.20261103221822-85ba0a9a70d8"}), "0.1.14"},
{"npm's 0.1.17 on the seat gives 0.1.18", known([]string{"0.1.17", "0.1.3"}, nil, nil), "0.1.18"},
{"another series and a tagged version count nothing", known([]string{"0.2.40", "0.1.9-feat-x.1"}, nil, nil), "0.1.0"},
{"the highest of the three", known([]string{"0.1.4"}, []string{"v0.1.9"}, []string{"v0.1.7"}), "0.1.10"},
} {
if got := Next(nil, "0.1", c.floor); got != c.want {
t.Errorf("%s: Next = %s, want %s", c.name, got, c.want)
}
}
if got := Next([]Entry{{Version: "0.1.20", Series: "0.1"}, {Version: "0.1.21-x.1", Series: "0.1", Tag: "x"}}, "0.1", known([]string{"0.1.3"}, nil, nil)); got != "0.1.21" {
t.Errorf("Next above the state's own = %s, want 0.1.21", got)
}
})
t.Run("decide", func(t *testing.T) {
pub := Entry{Name: "n", Kind: KindPackage, Series: "0.1", Version: "0.1.5", Revision: "r1", Fingerprint: "fA", State: Published}
ref := pub
ref.State, ref.Version, ref.Revision = Refused, "0.1.6", "r2"
img := Entry{Name: "i", Kind: KindBundle, Series: "0.1", Version: "0.1.2", Fingerprint: "fB", State: Published}
silent := Floor{Silent: []string{SourceSeat}}
for _, c := range []struct {
name string
entries []Entry
kind, fp, rev string
floor Floor
version string
keep, publish, unnum bool
wait bool
}{
{"a package's revision held published keeps its version and publishes nothing", []Entry{pub}, KindPackage, "fX", "r1", silent, "0.1.5", true, false, false, false},
{"a revision numbered but refused is published by its second build under the same version", []Entry{pub, ref}, KindPackage, "fY", "r2", known(nil, nil, nil), "0.1.6", true, true, false, false},
{"a new revision takes the next", []Entry{pub, ref}, KindPackage, "fZ", "r3", known(nil, nil, nil), "0.1.7", false, true, false, false},
{"a bundle's fingerprint keeps its number", []Entry{img}, KindBundle, "fB", "", silent, "0.1.2", true, false, false, false},
{"an unknown floor builds a bundle unnumbered", nil, KindBundle, "fC", "", silent, "", false, true, true, false},
{"an unknown floor builds an image unnumbered", nil, KindImage, "fC", "", silent, "", false, true, true, false},
{"an unknown floor makes a package wait", nil, KindPackage, "fC", "r9", silent, "", false, false, false, true},
} {
d := Decide(c.entries, c.kind, "0.1", c.fp, c.rev, c.floor)
if d.Version != c.version || d.Keep != c.keep || d.Publish != c.publish || d.Unnumbered != c.unnum || d.Wait != c.wait || d.Why == "" {
t.Errorf("%s: Decide = %+v", c.name, d)
}
}
})
t.Run("two claims never one number", func(t *testing.T) {
st := newMem()
v := Versions{Store: st, Now: func() time.Time { return time.Unix(0, 0) }}
ctx := context.Background()
st.before = func() { // a second claim takes 0.1.0 between the first's read and its create
if _, _, err := (Versions{Store: st}).Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f2"}); err != nil {
t.Error(err)
}
}
d, e, err := v.Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f1"})
if err != nil || d.Version != "0.1.1" || e.State != Numbered || e.Series != DefaultSeries {
t.Fatalf("Number = %+v, %+v, %v, want 0.1.1 after the other claim's 0.1.0", d, e, err)
}
if d, _, _ := v.Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f1"}); !d.Keep || d.Version != "0.1.1" {
t.Errorf("a numbered fingerprint claimed again = %+v, want it kept", d)
}
got, err := v.Mark(ctx, "n", "0.1.1", func(e *Entry) { e.State = Published })
if err != nil || got.State != Published {
t.Errorf("Mark = %+v, %v", got, err)
}
if _, err := v.Mark(ctx, "n", "0.9.9", func(*Entry) {}); err == nil {
t.Error("marking a version never numbered is no error")
}
})
t.Run("recorded", func(t *testing.T) {
st := newMem()
v := Versions{Store: st}
ctx := context.Background()
if _, _, err := v.Number(ctx, Claim{Name: "n", Kind: KindImage, Fingerprint: "f", Digest: "sha256:aa", Floor: known(nil, nil, nil)}); err != nil {
t.Fatal(err)
} }
for _, c := range []struct { for _, c := range []struct {
version, digest string version, digest string
ok bool ok bool
}{{"0.1.0", "sha256:aa", true}, {"0.1.0", "sha256:bb", false}, {"0.1.7", "sha256:aa", false}} { }{{"0.1.4", "sha256:aa", true}, {"0.1.4", "sha256:bb", false}, {"0.1.7", "sha256:aa", false}} {
if _, ok, why, err := v.Recorded(ctx, "n", c.version, c.digest); err != nil || ok != c.ok || (!ok && why == "") { a, err := AnswerVersions("m/program", c.version, c.digest, reserve)
t.Errorf("Recorded(%s, %s) = %v, %q, %v; want %v", c.version, c.digest, ok, why, err, c.ok) if err != nil || a.Recorded == nil || *a.Recorded != c.ok || (!c.ok && a.Why == "") || a.Reserved == nil || asked != "m/program@"+c.version {
t.Errorf("builder_versions(%s, %s) = %+v, %v, asked %s; want recorded %v from the reservation", c.version, c.digest, a, err, asked, c.ok)
} }
} }
// builder_versions answers the same through the tools bundle's read-only view. // A digest not recorded yet takes the publish (A-490j); a name the reservation does not know is a no naming it.
r := Reader{Keys: func() ([]string, error) { unbuilt := func(string, string) (meshbuilds.ReservedAnswer, error) {
var all []string return meshbuilds.ReservedAnswer{Module: "m", Version: "0.1.5", Artifacts: []meshbuilds.ReservedAnswerArtifactsItem{{Artifact: "m:program"}}}, nil
for k := range st.vals {
all = append(all, k)
}
return all, nil
}, Get: func(k string) (json.RawMessage, bool, error) {
v, _, ok, err := st.Get(ctx, k)
return v, ok, err
}}
a, err := AnswerVersions(ctx, r, "n", "0.1.0", "sha256:bb")
if err != nil || len(a.Versions) != 1 || a.Recorded == nil || *a.Recorded || a.Why == "" {
t.Errorf("builder_versions = %+v, %v; want one version and not recorded for another digest", a, err)
} }
if _, err := AnswerVersions(ctx, r, " ", "", ""); err == nil { if a, _ := AnswerVersions("m/program", "0.1.5", "sha256:cc", unbuilt); a.Recorded == nil || !*a.Recorded {
t.Errorf("an artifact with no digest recorded yet = %+v, want recorded", a)
}
unknown := func(string, string) (meshbuilds.ReservedAnswer, error) {
return meshbuilds.ReservedAnswer{Error: "no entry carries the name x"}, nil
}
if a, _ := AnswerVersions("x", "0.1.0", "sha256:aa", unknown); a.Recorded == nil || *a.Recorded || !strings.Contains(a.Why, "no entry carries") {
t.Errorf("a name no entry carries = %+v, want not recorded naming it", a)
}
if a, err := AnswerVersions("m/program", "", "", reserve); err != nil || a.Recorded != nil || a.Reserved == nil {
t.Errorf("builder_versions with no version = %+v, %v; want the reservation alone", a, err)
}
if _, err := AnswerVersions(" ", "", "", reserve); err == nil {
t.Error("builder_versions with no name answered") t.Error("builder_versions with no name answered")
} }
}) })
t.Run("the floor wakes on its silent source, never a timer", func(t *testing.T) {
ctx := context.Background()
src := FloorSources{
Seat: func(context.Context, string, string) ([]string, error) { return []string{"0.1.3"}, nil },
Tags: func(context.Context, string, string) ([]string, error) { return nil, errors.New("no answer") },
Requirements: func(context.Context, string) ([]string, error) { return nil, nil },
}
f, why := src.Ask(ctx, FloorOf{Seat: "oci-artifact-registry", Name: "m/program"})
if f.Known() || !reflect.DeepEqual(f.Silent, []string{SourceTags}) || why[SourceTags] != "no answer" {
t.Fatalf("Ask = %+v, %v; want git.tags silent", f, why)
}
holders := map[string]string{SourceSeats[SourceTags]: "mesh-delivery-forge-bridge", SourceSeats[SourceRequirements]: "mesh-delivery-indexer"}
fw := FloorWaits{Holder: func(seat string) (string, bool) { h, ok := holders[seat]; return h, ok }}
w := fw.Wait("m/program", "oci-artifact-registry", "distribution", f, why, time.Unix(0, 0))
if !strings.Contains(w.Finding(), "git.tags (no answer)") {
t.Errorf("finding = %q", w.Finding())
}
for _, c := range []struct {
kind, seat, module, name string
want []string
}{
{WakePublished, "oci-artifact-registry", "", "", nil}, // the seat answered already: a publish wakes nothing
{WakeTakenIn, "", "", "", nil},
{WakeRevision, "", "", "", []string{"m/program"}},
{WakeCleared, "", "mesh-delivery-forge-bridge", "", []string{"m/program"}}, // recovered with nothing to say
{WakeCleared, "", "mesh-delivery-indexer", "", nil},
{WakeByHand, "", "", "m/program", []string{"m/program"}},
{WakeByHand, "", "", "other", nil},
} {
if got := fw.Wake(c.kind, c.seat, c.module, c.name); !reflect.DeepEqual(got, c.want) {
t.Errorf("Wake(%s %s %s %s) = %v, want %v", c.kind, c.seat, c.module, c.name, got, c.want)
}
}
seatDown := Floor{Silent: []string{SourceSeat}}
fw.Wait("distribution/program", "container-image-registry", "distribution", seatDown, nil, time.Unix(0, 0))
if got := fw.Wake(WakePublished, "container-image-registry", "", ""); !reflect.DeepEqual(got, []string{"distribution/program"}) {
t.Errorf("the holder's published woke %v, want its own image's name", got)
}
if got := fw.Wake(WakeCleared, "", "distribution", ""); !reflect.DeepEqual(got, []string{"distribution/program"}) {
t.Errorf("the holder's clear woke %v", got)
}
if !fw.Answered("m/program") || fw.Answered("m/program") || len(fw.Waiting()) != 1 {
t.Error("Answered drops the wait once")
}
// DLV-B4: the waits are kept in floor-waits; a restarted builder takes them in, and its sources' events still wake them.
kept := keeperMem{}
restarted := &FloorWaits{}
restarted.Keep(kept, []FloorWait{{Name: "m/held", Seat: SeatImages, Silent: []string{SourceTags}, Since: time.Unix(5, 0)}})
if got := restarted.Wake(WakeRevision, "", "", ""); !reflect.DeepEqual(got, []string{"m/held"}) {
t.Errorf("a wait held in floor-waits woke %v after a restart, want m/held", got)
}
restarted.Wait("m/new", SeatNPM, "", Floor{Silent: []string{SourceSeat}}, nil, time.Unix(9, 0))
ans, err := AnswerFloorWaits(Reader{Keys: kept.keys, Get: kept.get})
if err != nil || len(ans.Waits) != 2 || ans.Waits[0].Name != "m/held" || ans.Waits[1].Name != "m/new" || !strings.Contains(ans.Waits[1].Finding, "seat did not answer") {
t.Fatalf("builder_floor_waits = %+v, %v", ans, err)
}
restarted.Answered("m/held")
if _, ok := kept[FloorWaitKey("m/held")]; ok {
t.Error("an answered floor stays in floor-waits")
}
// The lead's ruling (review round 1): builder_bounds lists each key of the state bounds with what it bounds and
// when it ends.
at := time.Date(2026, 11, 4, 17, 0, 0, 0, time.UTC)
bounds := keeperMem{PublishBoundKey("m/program", "0.1.4"): EncodeBound("the publish of m/program@0.1.4 to oci-artifact-registry", at.Add(PublishBound)),
OldFormBoundKey("g14"): EncodeBound("the seven days g14 holds the old form's window", at.Add(FindingAfter))}
rows, err := AnswerBounds(Reader{Keys: bounds.keys, Get: bounds.get}, at)
if err != nil || len(rows) != 2 || rows[0].Key != OldFormBoundKey("g14") || rows[1].Left != "10m0s" ||
!strings.Contains(rows[1].Bounds, "m/program@0.1.4") || !rows[0].Ends.Equal(at.Add(FindingAfter)) {
t.Fatalf("builder_bounds = %+v, %v", rows, err)
}
})
t.Run("old form", func(t *testing.T) { t.Run("old form", func(t *testing.T) {
// One kind, a first form and a newer one. // One kind, a first form and a newer one.
fs := forms.ArtifactForms{{Name: "registry", First: true, Kinds: []string{"image"}}, {Name: "oci", Kinds: []string{"image"}}} fs := forms.ArtifactForms{{Name: "registry", First: true, Kinds: []string{"image"}}, {Name: "oci", Kinds: []string{"image"}}}
@@ -368,221 +191,4 @@ func TestTheBuildersVersions(t *testing.T) {
t.Error("a closed window closes again: old-form-closed would be said twice") t.Error("a closed window closes again: old-form-closed would be said twice")
} }
}) })
t.Run("at the claim", func(t *testing.T) {
ctx := context.Background()
tagsUp := false
var asked []string
src := FloorSources{
Seat: func(context.Context, string, string) ([]string, error) { return []string{"0.1.3"}, nil },
Tags: func(_ context.Context, repo, prefix string) ([]string, error) {
asked = append(asked, repo+" "+prefix)
if !tagsUp {
return nil, errors.New("no answer")
}
return []string{"go/v0.1.13"}, nil
},
Requirements: func(context.Context, string) ([]string, error) { return nil, nil },
}
fw := &FloorWaits{}
n := &Numberer{Versions: Versions{Store: newMem()}, Floor: src, Waits: fw}
c := BuildClaim{Module: "m", Path: "go", Repository: "novox/m", Fingerprint: "fp1", Commit: "c1", Revision: "7", Merge: 7,
Artifacts: []ClaimArtifact{{Artifact: "program", Kind: KindBundle, Language: "go"}, {Artifact: "base", Kind: "upstream"}}}
got, err := n.Number(ctx, c)
if err != nil || len(got.Versions) != 0 || !reflect.DeepEqual(got.Unnumbered, []string{"program"}) || got.Wait != "" {
t.Fatalf("silent floor: %+v, %v; want program unnumbered, the upstream copy left out", got, err)
}
if !reflect.DeepEqual(asked, []string{"novox/m go/v"}) || len(fw.Waiting()) != 1 {
t.Fatalf("asked %v, waits %+v", asked, fw.Waiting())
}
pkg := c
pkg.Artifacts = []ClaimArtifact{{Artifact: "lib", Kind: KindPackage, Language: "go"}}
if got, _ := n.Number(ctx, pkg); got.Wait == "" || len(got.Versions) != 0 {
t.Fatalf("a package with no floor = %+v; want it to wait", got)
}
tagsUp = true
got, err = n.Number(ctx, c)
if err != nil || got.Versions["program"] != "0.1.14" || len(fw.Waiting()) != 1 {
t.Fatalf("floor answered: %+v, %v, waits %+v; want 0.1.14, lib still waiting", got, err, fw.Waiting())
}
got, _ = n.Number(ctx, c)
var publishing []string // review round 1: a version built and still numbered arms its publish bound
n.Publishing = func(_ context.Context, e Entry) { publishing = append(publishing, e.Name+"@"+e.Version) }
if err := n.Built(ctx, c, got, map[string]string{"program": "sha256:aa"}); err != nil {
t.Fatal(err)
}
if n.Publishing = nil; !reflect.DeepEqual(publishing, []string{"m/program@0.1.14"}) {
t.Fatalf("the publish bounds armed: %v, want m/program@0.1.14", publishing)
}
again, _ := n.Number(ctx, c)
if again.Versions["program"] != "0.1.14" || len(asked) != 3 {
t.Fatalf("again: %+v, asked %v; want the number kept, the floor not asked", again, asked)
}
if _, ok, why, _ := n.Versions.Recorded(ctx, "m/program", "0.1.14", "sha256:bb"); ok {
t.Fatalf("another digest recorded: %s", why)
}
// DLV-B4: the seat's events move the entry; a published wakes the names waiting on that seat.
if wake, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e1", Outcome{Name: "m/other", Digest: "sha256:cc"}); err != nil || len(wake) != 0 {
t.Fatalf("a by-digest publish of another seat's wait: %v, %v", wake, err)
}
n.Waits.Wait("m/lib", SeatGoPackages, "", Floor{Silent: []string{SourceSeat}}, nil, time.Unix(0, 0))
if wake, _ := n.Heard(ctx, SeatGoPackages, HeardPublished, "e2", Outcome{Name: "m/x", Digest: "sha256:dd"}); !reflect.DeepEqual(wake, []string{"m/lib"}) {
t.Fatalf("a published on the Go seat woke %v, want m/lib, whose seat was silent", wake)
}
// Design 47 G §369, A-415; ADR 0605 §4: a published of other bytes under the number is the reservation's, never this entry's.
if _, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e5", Outcome{Name: "m/program", Version: "0.1.14", Digest: "sha256:new"}); !errors.Is(err, ErrNotNumbered) {
t.Fatalf("a published of other bytes under 0.1.14: %v, want ErrNotNumbered", err)
}
if all, _ := n.Versions.Of(ctx, "m/program"); all[0].State != Numbered || all[0].Digest != "sha256:aa" {
t.Fatalf("after a published of other bytes: %+v, want it numbered with sha256:aa", all[0])
}
for _, h := range []struct{ event, state, reason string }{{HeardRefused, Refused, "bytes differ"}, {HeardPublished, Published, ""}, {HeardRefused, Published, ""}, {HeardRemoved, Removed, "retention"}} {
if _, err := n.Heard(ctx, SeatArtifacts, h.event, "e3", Outcome{Name: "m/program", Version: "0.1.14", Digest: "sha256:aa", Reason: h.reason}); err != nil {
t.Fatal(err)
}
all, _ := n.Versions.Of(ctx, "m/program")
if all[0].State != h.state {
t.Fatalf("after %s: %+v, want %s", h.event, all[0], h.state)
}
}
if _, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e4", Outcome{Name: "m/none", Version: "0.1.0"}); err == nil {
t.Fatal("a published of a version the builder never numbered is not said")
}
// D-B5 (ADR 0666 §15, design 51 *The versions* line 287): a package's build whose published versions cannot be read
// is refused, naming the state; a bundle's is built as before (ADR 0617 §1), the error said.
st := n.Versions.Store.(*mem)
st.down = errors.New("nats: no responders available for request")
if got, err := n.Number(ctx, pkg); err != nil || !strings.Contains(got.Refused, "state versions cannot be read") || len(got.Versions) != 0 {
t.Errorf("a package with its versions unread = %+v, %v; want refused naming the state", got, err)
}
if got, err := n.Number(ctx, c); err == nil || got.Refused != "" {
t.Errorf("a bundle with its versions unread = %+v, %v; want the error, no refusal", got, err)
}
st.down = nil
})
t.Run("a package is numbered under its name in its ecosystem", func(t *testing.T) {
// design 32: the indexer's packages state names, in each series key, the package's name and the <module>/<artifact>
// it is built from; the builder numbers, asks the floor of and records the package under that name.
ctx := context.Background()
state := packagesMem{
"git=2enovox=2ebe/novox/mesh-sdk/go.0.1": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.1"}`),
"@novox/mesh-sdk.0.1": []byte(`{"v":1,"name":"@novox/mesh-sdk","package":"mesh-sdk/ts","series":"0.1"}`),
"git=2enovox=2ebe/novox/mesh-sdk/go": []byte(`{"v":1,"module":"git.novox.be/novox/mesh-sdk/go"}`),
"broken.0.1": []byte(`not json`),
}
var floorOf []string
src := FloorSources{
Seat: func(_ context.Context, _, name string) ([]string, error) {
floorOf = append(floorOf, name)
return []string{"0.1.3"}, nil
},
Tags: func(context.Context, string, string) ([]string, error) { return nil, nil },
Requirements: func(_ context.Context, name string) ([]string, error) {
floorOf = append(floorOf, name)
return nil, nil
},
}
n := &Numberer{Versions: Versions{Store: newMem()}, Floor: src, Names: NamesIn(state)}
c := BuildClaim{Module: "mesh-sdk", Path: "go", Repository: "novox/mesh-sdk", Fingerprint: "fp1", Commit: "c1", Revision: "3", Merge: 3,
Artifacts: []ClaimArtifact{{Artifact: "go", Kind: KindPackage, Language: "go"}, {Artifact: "ts", Kind: KindPackage, Language: "typescript"},
{Artifact: "new", Kind: KindPackage, Language: "go"}, {Artifact: "program", Kind: KindBundle, Language: "go"}}}
got, err := n.Number(ctx, c)
if err != nil || got.Versions["go"] != "0.1.4" || got.Versions["ts"] != "0.1.4" || !reflect.DeepEqual(got.Unnumbered, []string{"new"}) {
t.Fatalf("Number = %+v, %v; want go and ts numbered, new unnumbered (no name yet)", got, err)
}
if got.Names["go"] != "git.novox.be/novox/mesh-sdk/go" || got.Names["ts"] != "@novox/mesh-sdk" || got.Names["program"] != "mesh-sdk/program" {
t.Errorf("names = %v", got.Names)
}
if !slices.Contains(floorOf, "git.novox.be/novox/mesh-sdk/go") || slices.Contains(floorOf, "mesh-sdk/go") {
t.Errorf("the floor was asked of %v, want the Go module path", floorOf)
}
if es, _ := n.Versions.Of(ctx, "git.novox.be/novox/mesh-sdk/go"); len(es) != 1 || es[0].Version != "0.1.4" {
t.Errorf("versions of the Go module path = %+v", es)
}
if es, _ := n.Versions.Of(ctx, "mesh-sdk/go"); len(es) != 0 {
t.Errorf("numbered under the builder's name too: %+v", es)
}
if err := n.Built(ctx, c, got, map[string]string{"go": "sha256:aa"}); err != nil {
t.Fatal(err)
}
if es, _ := n.Versions.Of(ctx, "git.novox.be/novox/mesh-sdk/go"); len(es) != 1 || es[0].Digest != "sha256:aa" {
t.Errorf("the built digest is not recorded under the name: %+v", es)
}
// The indexer writes the name of `new` later: its series key names the module, and the look at the done build
// numbers it with the done key's digest; the rest are kept.
state["new.0.1"] = []byte(`{"v":1,"name":"new","package":"mesh-sdk/new","series":"0.1"}`)
for key, want := range map[string]string{"new.0.1": "mesh-sdk", "git=2enovox=2ebe/novox/mesh-sdk/go": "", "broken.0.1": ""} {
if module, name, ok := NamedModule(key, state[key]); module != want || ok != (want != "") || (ok && name != "new") {
t.Errorf("NamedModule(%s) = %q, %q, %v, want %q", key, module, name, ok, want)
}
}
done := c
done.Done = map[string]string{"go": "sha256:aa", "new": "sha256:bb"}
late, err := n.Number(ctx, done)
if err != nil || late.Versions["new"] != "0.1.4" || late.Versions["go"] != "0.1.4" || len(late.Unnumbered) != 0 {
t.Fatalf("a look at the done build = %+v, %v; want new numbered and go kept", late, err)
}
if es, _ := n.Versions.Of(ctx, "new"); len(es) != 1 || es[0].Digest != "sha256:bb" {
t.Errorf("versions of new = %+v, want its done digest recorded", es)
}
if _, _, err := NamesIn(packagesMem(nil).failing())(ctx, "m", "a"); err == nil {
t.Error("a packages state that cannot be read is no error")
}
// A packages state not on the bus yet leaves the package unnumbered, said, and numbers the rest of the claim.
n.Names = NamesIn(packagesMem(nil).failing())
bare, err := n.Number(ctx, c)
if err != nil || !reflect.DeepEqual(bare.Unnumbered, []string{"go", "new", "ts"}) || bare.Versions["program"] == "" ||
!strings.Contains(bare.Said[0].Line, "cannot be read") {
t.Errorf("an unreadable packages state: %+v, %v", bare, err)
}
})
t.Run("fill", func(t *testing.T) {
if _, full := Fill(Cap*79/100, Cap); full {
t.Error("79 % is full")
}
if _, full := Fill((Cap*80+99)/100, Cap); !full {
t.Error("80 % is not full")
}
})
t.Run("fresh claims and the floor", func(t *testing.T) {
ctx := context.Background()
// A fresh claim of a published fingerprint takes the next number; the old one stays.
st := newMem()
v := Versions{Store: st}
raw, _ := Encode(Entry{Name: "m/p", Kind: KindBundle, Series: "0.1", Version: "0.1.3", Fingerprint: "f1", State: Published, At: time.Unix(1, 0)})
_, _ = st.Create(ctx, Key("m/p", "0.1.3"), raw)
if d, _, err := v.Number(ctx, Claim{Name: "m/p", Kind: KindBundle, Fingerprint: "f1"}); err != nil || d.Version != "0.1.3" || !d.Keep {
t.Fatalf("a published fingerprint keeps its number: %+v %v", d, err)
}
if d, e, err := v.Number(ctx, Claim{Name: "m/p", Kind: KindBundle, Fingerprint: "f1", Fresh: true}); err != nil || d.Version != "0.1.4" || d.Keep || e.Fingerprint != "f1" {
t.Fatalf("a fresh claim takes the next number: %+v %+v %v", d, e, err)
}
// A refusal records the digest refused; Built replaces a digest no published was said for, never a published one.
n := &Numberer{Versions: v}
_, _ = n.Heard(ctx, SeatArtifacts, HeardRefused, "r1", Outcome{Name: "m/p", Version: "0.1.4", Digest: "sha256:old", Reason: "x"})
if es, _ := v.Of(ctx, "m/p"); es[1].RefusedDigest != "sha256:old" {
t.Errorf("refused records no digest: %+v", es[1])
}
_, _ = v.Mark(ctx, "m/p", "0.1.4", func(e *Entry) { e.Digest = "sha256:old" })
bc := BuildClaim{Module: "m"}
_ = n.Built(ctx, bc, Numbering{Versions: map[string]string{"p": "0.1.4"}}, map[string]string{"p": "sha256:new"})
_, _ = v.Mark(ctx, "m/p", "0.1.3", func(e *Entry) { e.Digest = "sha256:held" })
_ = n.Built(ctx, bc, Numbering{Versions: map[string]string{"p": "0.1.3"}}, map[string]string{"p": "sha256:other"})
es, _ := v.Of(ctx, "m/p")
if es[0].Digest != "sha256:held" || es[1].Digest != "sha256:new" {
t.Errorf("Built: published %s (want sha256:held), refused %s (want sha256:new)", es[0].Digest, es[1].Digest)
}
if all, err := v.All(ctx); err != nil || len(all) != 2 {
t.Errorf("All = %d entries, %v", len(all), err)
}
_, _ = v.Mark(ctx, "m/p", "0.1.4", func(e *Entry) { e.State = Published })
acts := Acts{Numberer: &Numberer{Versions: v, Waits: &FloorWaits{}}, Reconsider: func(context.Context) {}}
reconsidered := false
acts.Reconsider = func(context.Context) { reconsidered = true }
// H-A-159: the builder numbers nothing of its own, so no claim asks a floor: the tool refuses, saying so, and does nothing.
for _, name := range []string{"m/p", "m/new"} {
if ans, err := acts.FloorAgain(ctx, name); err == nil || !strings.Contains(err.Error(), "numbers nothing of its own") || reconsidered {
t.Errorf("floor again of %s: %q %v, looked again %v; want refused naming H-A-159, nothing looked at", name, ans, err, reconsidered)
}
}
})
} }
+21 -18
View File
@@ -122,7 +122,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
if m.Module != "mesh-delivery-builder" { if m.Module != "mesh-delivery-builder" {
t.Errorf("module = %q", m.Module) t.Errorf("module = %q", m.Module)
} }
if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "floor-waits", History: 1, MaxMiB: 8}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, MaxMiB: 1}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "versions", History: 1, MaxMiB: 32}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814) if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, MaxMiB: 1}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814)
t.Errorf("state = %+v, want %+v", m.State, want) t.Errorf("state = %+v, want %+v", m.State, want)
} }
// 1887/A4c: the builder chooses no node, so it reads neither presence nor have, invokes no build module's tool and // 1887/A4c: the builder chooses no node, so it reads neither presence nor have, invokes no build module's tool and
@@ -149,10 +149,10 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
t.Errorf("reads %s: the indexer's and the assigner's state is read by their tools and views families alone", r) t.Errorf("reads %s: the indexer's and the assigner's state is read by their tools and views families alone", r)
} }
} }
// Design 51 *The floor*: the floor's three sources, the registry seats' versions, git.tags and indexer_requirements. // Design 47 H §756: the floor goes, and with it its source git.tags; the registry seats' versions are asked of a number a
// registry holds (H-A-275) and of a package's published versions (H-A-194).
// The watchdogs seat's presence says a node's machine is heard (issue 1966, ADR 0596 §2, ADR 0668 §3). // The watchdogs seat's presence says a node's machine is heard (issue 1966, ADR 0596 §2, ADR 0668 §3).
if want := []string{"seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.seat-definitions", "seat:mesh-catalog.revision", "seat:mesh-delivery.source", "seat:container-image-registry.publish", "seat:container-image-registry.remove", "seat:container-image-registry.versions", if want := []string{"seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.seat-definitions", "seat:mesh-catalog.revision", "seat:mesh-delivery.source", "seat:container-image-registry.publish", "seat:container-image-registry.remove", "seat:container-image-registry.versions",
"seat:git.tag", "seat:git.tags",
"seat:go-package-registry.publish", "seat:go-package-registry.remove", "seat:go-package-registry.versions", "seat:mesh-artifact-sweep.held", "seat:mesh-builds.reserved", "seat:mesh-builds.drop", "seat:mesh-builds.publish-queue", "seat:mesh-catalog.versions", "seat:mesh-hand-acts.hand-act", "seat:mesh-module-assigner.assignments", "seat:mesh-watchdogs.presence", "seat:node-build-go.drop", "seat:node-build-image.drop", "seat:node-build-node.drop", "seat:node-build-go.answer", "seat:node-build-image.answer", "seat:node-build-node.answer", "seat:node-engine.manifest-reads", "seat:npm-package-registry.publish", "seat:npm-package-registry.remove", "seat:go-package-registry.publish", "seat:go-package-registry.remove", "seat:go-package-registry.versions", "seat:mesh-artifact-sweep.held", "seat:mesh-builds.reserved", "seat:mesh-builds.drop", "seat:mesh-builds.publish-queue", "seat:mesh-catalog.versions", "seat:mesh-hand-acts.hand-act", "seat:mesh-module-assigner.assignments", "seat:mesh-watchdogs.presence", "seat:node-build-go.drop", "seat:node-build-image.drop", "seat:node-build-node.drop", "seat:node-build-go.answer", "seat:node-build-image.answer", "seat:node-build-node.answer", "seat:node-engine.manifest-reads", "seat:npm-package-registry.publish", "seat:npm-package-registry.remove",
"seat:npm-package-registry.versions", "seat:oci-artifact-registry.publish", "seat:oci-artifact-registry.remove", "seat:oci-artifact-registry.versions", "seat:npm-package-registry.versions", "seat:oci-artifact-registry.publish", "seat:oci-artifact-registry.remove", "seat:oci-artifact-registry.versions",
// A-231: the build asks on each build seat's queue delivery (accept.delivery.<asker>). // A-231: the build asks on each build seat's queue delivery (accept.delivery.<asker>).
@@ -162,14 +162,13 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
// The builder hears the build seats' toolchain-reported and the node-engine seat's running (design 47 G §492, §546) and reads no // The builder hears the build seats' toolchain-reported and the node-engine seat's running (design 47 G §492, §546) and reads no
// build module's toolchains; and by the seat mesh-artifact-sweep's artifacts-gone, a blob the sweep found gone (1937/AC4, 1955/L7), the // build module's toolchains; and by the seat mesh-artifact-sweep's artifacts-gone, a blob the sweep found gone (1937/AC4, 1955/L7), the
// controller's no longer (1126/B9, ADR 0590). // controller's no longer (1126/B9, ADR 0590).
// Design 51 *The floor*: the indexer's take-in.taken (design 47 H H-A-116) and the condition keeper's condition-cleared wake // Design 47 H §756: the floor and its wait go, so neither the indexer's take-in.taken (H-A-116) nor condition-cleared is heard.
// a silent floor.
// DLV-B4: the four registry seats' outcomes, each a seat event `<seat>.<event>` on the shared events stream. // DLV-B4: the four registry seats' outcomes, each a seat event `<seat>.<event>` on the shared events stream.
// DLV-M1: the indexer's and the assigner's views families of the states it follows. // DLV-M1: the indexer's and the assigner's views families of the states it follows.
if want := []string{"container-image-registry.kept", "container-image-registry.published", "container-image-registry.refused", "container-image-registry.removed", if want := []string{"container-image-registry.kept", "container-image-registry.published", "container-image-registry.refused", "container-image-registry.removed",
"go-package-registry.kept", "go-package-registry.published", "go-package-registry.refused", "go-package-registry.removed", "go-package-registry.kept", "go-package-registry.published", "go-package-registry.refused", "go-package-registry.removed",
"mesh-artifact-sweep.artifacts-gone", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-catalog.version-released", "mesh-catalog.versions-filled", "mesh-artifact-sweep.artifacts-gone", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-catalog.version-released",
"mesh-conditions.condition-cleared", "mesh-conditions.findings-asked", "mesh-delivery-indexer.take-in.taken", "seat:mesh-module-assigner.views.assignments", "mesh-conditions.findings-asked", "seat:mesh-module-assigner.views.assignments",
"seat:mesh-module-assigner.views.seat-holders", // A-298: the claimant's seat-holders view resolves the callers' seat entries "seat:mesh-module-assigner.views.seat-holders", // A-298: the claimant's seat-holders view resolves the callers' seat entries
"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "node-build-go.toolchain-reported", "node-build-node.toolchain-reported", "node-engine.manifest-reads-changed", "node-engine.running", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "node-build-go.toolchain-reported", "node-build-node.toolchain-reported", "node-engine.manifest-reads-changed", "node-engine.running",
"npm-package-registry.kept", "npm-package-registry.published", "npm-package-registry.refused", "npm-package-registry.removed", "npm-package-registry.kept", "npm-package-registry.published", "npm-package-registry.refused", "npm-package-registry.removed",
@@ -185,7 +184,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
} }
// 1945: the builder's tools (builder_seat_queue: note 62), served by its tools bundle, and the event it says when it asks an ask again. // 1945: the builder's tools (builder_seat_queue: note 62), served by its tools bundle, and the event it says when it asks an ask again.
if want := []string{"build_current", "builder_announce_again", "builder_ask_again", "builder_ask_drop", "builder_asks", "builder_bounds", "builder_build", "builder_build_again", "builder_builds_since", "builder_engine_reads", "builder_first_view_again", "builder_first_views", if want := []string{"build_current", "builder_announce_again", "builder_ask_again", "builder_ask_drop", "builder_asks", "builder_bounds", "builder_build", "builder_build_again", "builder_builds_since", "builder_engine_reads", "builder_first_view_again", "builder_first_views",
"builder_floor_again", "builder_floor_waits", "builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserve_done", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) { "builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserve_done", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) {
t.Errorf("tools = %v, want %v", m.Tools, want) t.Errorf("tools = %v, want %v", m.Tools, want)
} }
// Design 47 G §672: the toolchain waits' stream, kept 7 days within 16 MiB, and the bound's setting, 60 minutes. // Design 47 G §672: the toolchain waits' stream, kept 7 days within 16 MiB, and the bound's setting, 60 minutes.
@@ -199,15 +198,17 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
m.Streams[3].Duplicates != 24 || m.Streams[3].MaxDeliveries != 10 || m.Streams[3].MaxAgeDays != 7 || m.Streams[3].MaxMiB != 64 { m.Streams[3].Duplicates != 24 || m.Streams[3].MaxDeliveries != 10 || m.Streams[3].MaxAgeDays != 7 || m.Streams[3].MaxMiB != 64 {
t.Errorf("streams = %+v, want waits with wait-held.** and wait-ended.**, 7 days, 16 MiB, the builds' stream (build.ended.**, 7 days, kept last per subject: design 47 G A-181) and the findings' stream", m.Streams) t.Errorf("streams = %+v, want waits with wait-held.** and wait-ended.**, 7 days, 16 MiB, the builds' stream (build.ended.**, 7 days, kept last per subject: design 47 G A-181) and the findings' stream", m.Streams)
} }
if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 12 || if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 13 ||
// design 47 H2 §775, H-A-381 (2): the kept-call pace and the taken key's bound, read by the process // design 47 H2 §775, H-A-381 (2): the kept-call pace and the taken key's bound, read by the process
m.Config["kept-call-pace-first"].Default != "1s" || m.Config["kept-call-pace-max"].Default != "30s" || m.Config["ask-taken-bound"].Default != "10m" || m.Config["kept-call-pace-first"].Default != "1s" || m.Config["kept-call-pace-max"].Default != "30s" || m.Config["ask-taken-bound"].Default != "10m" ||
!m.Config["kept-call-pace-first"].Runtime || !m.Config["kept-call-pace-max"].Runtime || !m.Config["ask-taken-bound"].Runtime || !m.Config["kept-call-pace-first"].Runtime || !m.Config["kept-call-pace-max"].Runtime || !m.Config["ask-taken-bound"].Runtime ||
// H-A-461 (2): the bounds of §794 are settings read at run time, 100 ms and 5 minutes by default // H-A-461 (2): the bounds of §794 are settings read at run time, 100 ms and 5 minutes by default
m.Config["slow-event"].Default != "100ms" || m.Config["events-behind-bound"].Default != "5m" || !m.Config["slow-event"].Runtime || !m.Config["events-behind-bound"].Runtime || m.Config["slow-event"].Default != "100ms" || m.Config["events-behind-bound"].Default != "5m" || !m.Config["slow-event"].Runtime || !m.Config["events-behind-bound"].Runtime ||
m.Config["revision-wait-minutes"].Default != float64(2) || m.Config["package-wait-minutes"].Default != float64(10) || m.Config["revision-wait-minutes"].Default != float64(2) || m.Config["package-wait-minutes"].Default != float64(10) ||
// H-A-492: the record of a version's digests runs under the builder's own bound, a setting of 60 s by default
m.Config["record-bound-seconds"].Default != float64(60) ||
m.Config["publish-pause"].Default != float64(30) || m.Config["publish-pause-max"].Default != float64(30) || m.Config["publish-tries"].Default != float64(5) || m.Config["publish-tries"].Maximum != 10 { m.Config["publish-pause"].Default != float64(30) || m.Config["publish-pause-max"].Default != float64(30) || m.Config["publish-tries"].Default != float64(5) || m.Config["publish-tries"].Maximum != 10 {
t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), the publish settings 30 s, 30 min and 5 tries, at most 10 (design 47 G §588, §633, A-457a; H2 H-A-446 (2))", m.Config) t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), record-bound-seconds of 60 (H-A-492), the publish settings 30 s, 30 min and 5 tries, at most 10 (design 47 G §588, §633, A-457a; H2 H-A-446 (2))", m.Config)
} }
// Design 47 G §349: version.numbered is no longer said; old-form-closed on the family version, apart from the builds' ends. // Design 47 G §349: version.numbered is no longer said; old-form-closed on the family version, apart from the builds' ends.
if want := []string{"build.asked-again", "version.old-form-closed"}; !reflect.DeepEqual(m.Emits, want) { if want := []string{"build.asked-again", "version.old-form-closed"}; !reflect.DeepEqual(m.Emits, want) {
@@ -266,7 +267,7 @@ func TestManifestProcess(t *testing.T) { // 1607/AC1
t.Errorf("health = %v, want kind unit alone", p["health"]) t.Errorf("health = %v, want kind unit alone", p["health"])
} }
env, _ := p["env"].(map[string]any) env, _ := p["env"].(map[string]any)
if len(env) != 8 || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_TRIES_FILE"] != "${dir:state}/publish-tries" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" { if len(env) != 9 || env["MESH_BUILDER_RECORD_BOUND_FILE"] != "${dir:state}/record-bound-seconds" || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_TRIES_FILE"] != "${dir:state}/publish-tries" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" {
t.Errorf("env = %v, want the broker file and the path of the toolchain wait's file, never the setting itself (design 47 G §672, A-71)", p["env"]) t.Errorf("env = %v, want the broker file and the path of the toolchain wait's file, never the setting itself (design 47 G §672, A-71)", p["env"])
} }
for k, v := range env { for k, v := range env {
@@ -274,14 +275,16 @@ func TestManifestProcess(t *testing.T) { // 1607/AC1
t.Errorf("env %s = %v: a setting reaches the process as a file, never its environment (A-71)", k, v) t.Errorf("env %s = %v: a setting reaches the process as a file, never its environment (A-71)", k, v)
} }
} }
found := false for _, setting := range []string{"toolchain-wait-minutes", "record-bound-seconds"} { // H-A-492: the record's bound too
for _, r := range m.Resources { found := false
if r["type"] == "file" && r["path"] == "${dir:state}/toolchain-wait-minutes" && r["content"] == "${config:toolchain-wait-minutes}" { for _, r := range m.Resources {
found = true if r["type"] == "file" && r["path"] == "${dir:state}/"+setting && r["content"] == "${config:"+setting+"}" {
found = true
}
}
if !found {
t.Errorf("no file resource with the content ${config:%s}: A-71", setting)
} }
}
if !found {
t.Errorf("no file resource with the content ${config:toolchain-wait-minutes}: A-71")
} }
for _, r := range m.Resources { for _, r := range m.Resources {
if r["id"] == "settings" { if r["id"] == "settings" {
+17 -9
View File
@@ -25,8 +25,6 @@
"builder_build_again", "builder_build_again",
"builder_builds_since", "builder_builds_since",
"builder_engine_reads", "builder_engine_reads",
"builder_floor_again",
"builder_floor_waits",
"builder_old_form", "builder_old_form",
"builder_publish_again", "builder_publish_again",
"builder_publish_queue", "builder_publish_queue",
@@ -66,9 +64,6 @@
"mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed", "mesh-catalog.seat-definition-removed",
"mesh-catalog.version-released", "mesh-catalog.version-released",
"mesh-catalog.versions-filled",
"mesh-conditions.condition-cleared",
"mesh-delivery-indexer.take-in.taken",
"node-build-go.toolchain-reported", "node-build-go.toolchain-reported",
"node-build-node.toolchain-reported", "node-build-node.toolchain-reported",
"node-engine.manifest-reads-changed", "node-engine.manifest-reads-changed",
@@ -91,8 +86,6 @@
"invokes": [ "invokes": [
"seat:container-image-registry.remove", "seat:container-image-registry.remove",
"seat:container-image-registry.versions", "seat:container-image-registry.versions",
"seat:git.tag",
"seat:git.tags",
"seat:go-package-registry.remove", "seat:go-package-registry.remove",
"seat:go-package-registry.versions", "seat:go-package-registry.versions",
"seat:mesh-artifact-sweep.held", "seat:mesh-artifact-sweep.held",
@@ -134,7 +127,6 @@
{ "name": "builds", "history": 5, "max-mib": 128 }, { "name": "builds", "history": 5, "max-mib": 128 },
{ "name": "engine-reads", "history": 1, "max-mib": 8 }, { "name": "engine-reads", "history": 1, "max-mib": 8 },
{ "name": "findings", "history": 5, "max-mib": 32 }, { "name": "findings", "history": 5, "max-mib": 32 },
{ "name": "floor-waits", "history": 1, "max-mib": 8 },
{ "name": "hearing", "history": 1, "max-mib": 8 }, { "name": "hearing", "history": 1, "max-mib": 8 },
{ "name": "instances", "history": 1, "max-mib": 8 }, { "name": "instances", "history": 1, "max-mib": 8 },
{ "name": "old-form", "history": 1, "max-mib": 8 }, { "name": "old-form", "history": 1, "max-mib": 8 },
@@ -147,7 +139,6 @@
{ "name": "acted", "history": 1, "max-mib": 1 }, { "name": "acted", "history": 1, "max-mib": 1 },
{ "name": "asked", "history": 1, "max-mib": 8 }, { "name": "asked", "history": 1, "max-mib": 8 },
{ "name": "reasks", "history": 1, "max-mib": 8 }, { "name": "reasks", "history": 1, "max-mib": 8 },
{ "name": "versions", "history": 1, "max-mib": 32 },
{ "name": "first-views", "history": 1, "max-mib": 8 }, { "name": "first-views", "history": 1, "max-mib": 8 },
{ "name": "unbuildable", "history": 1, "max-mib": 8 }, { "name": "unbuildable", "history": 1, "max-mib": 8 },
{ "name": "consumers", "history": 1, "max-mib": 8 } { "name": "consumers", "history": 1, "max-mib": 8 }
@@ -183,6 +174,14 @@
"trusted": false, "trusted": false,
"default": 10 "default": 10
}, },
"record-bound-seconds": {
"type": "number",
"description": "seconds the builder gives the record of a version's digests after its build ends, under its own bound and never the build's (design 47 H2 H-A-492).",
"minimum": 1,
"maximum": 3600,
"trusted": false,
"default": 60
},
"ask-taken-bound": { "ask-taken-bound": {
"type": "string", "type": "string",
"description": "how long the builder keeps the id of an ask it took from the seat mesh-builds' work queue, so a repeat of it is taken once, a Go duration such as 10m (design 47 H2 §775; H-A-381 (2)).", "description": "how long the builder keeps the id of an ask it took from the seat mesh-builds' work queue, so a repeat of it is taken once, a Go duration such as 10m (design 47 H2 §775; H-A-381 (2)).",
@@ -310,6 +309,14 @@
"mode": "0600", "mode": "0600",
"content": "${config:package-wait-minutes}" "content": "${config:package-wait-minutes}"
}, },
{
"id": "record-bound",
"type": "file",
"path": "${dir:state}/record-bound-seconds",
"owner": "mesh-delivery-builder",
"mode": "0600",
"content": "${config:record-bound-seconds}"
},
{ {
"id": "publish-pause", "id": "publish-pause",
"type": "file", "type": "file",
@@ -361,6 +368,7 @@
"MESH_BUILDER_TOOLCHAIN_WAIT_FILE": "${dir:state}/toolchain-wait-minutes", "MESH_BUILDER_TOOLCHAIN_WAIT_FILE": "${dir:state}/toolchain-wait-minutes",
"MESH_BUILDER_REVISION_WAIT_FILE": "${dir:state}/revision-wait-minutes", "MESH_BUILDER_REVISION_WAIT_FILE": "${dir:state}/revision-wait-minutes",
"MESH_BUILDER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes", "MESH_BUILDER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes",
"MESH_BUILDER_RECORD_BOUND_FILE": "${dir:state}/record-bound-seconds",
"MESH_BUILDER_PUBLISH_PAUSE_FILE": "${dir:state}/publish-pause", "MESH_BUILDER_PUBLISH_PAUSE_FILE": "${dir:state}/publish-pause",
"MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE": "${dir:state}/publish-pause-max", "MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE": "${dir:state}/publish-pause-max",
"MESH_BUILDER_PUBLISH_TRIES_FILE": "${dir:state}/publish-tries", "MESH_BUILDER_PUBLISH_TRIES_FILE": "${dir:state}/publish-tries",
@@ -69,6 +69,12 @@ func TestManifestAndModuleValuesKeepTheirRules(t *testing.T) {
if m, err := DecodeModule(raw); err != nil || m.Fp2 != good.Fp2 || m.Path != RootPath { if m, err := DecodeModule(raw); err != nil || m.Fp2 != good.Fp2 || m.Path != RootPath {
t.Errorf("DecodeModule = %+v, %v", m, err) t.Errorf("DecodeModule = %+v, %v", m, err)
} }
// Design 47 H2 H-A-536, H-A-538: an import form with no imports is a reported empty import set.
empty := good
empty.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", ImportForm: SourcePrefix2 + hex64("a")}
if _, err := EncodeModule(empty); err != nil {
t.Errorf("a reported empty import set: %v", err)
}
refused := good refused := good
refused.Verdict, refused.Problems = VerdictRefused, []string{"p"} refused.Verdict, refused.Problems = VerdictRefused, []string{"p"}
if _, err := EncodeModule(refused); err != nil { if _, err := EncodeModule(refused); err != nil {
@@ -90,8 +96,8 @@ func TestManifestAndModuleValuesKeepTheirRules(t *testing.T) {
"a toolchain with no recipe": func(m *seat.ModulesByModuleValue) { "a toolchain with no recipe": func(m *seat.ModulesByModuleValue) {
m.Toolchains = map[string]seat.ToolchainUsed{"go": {Language: "go", Version: "1.26"}} m.Toolchains = map[string]seat.ToolchainUsed{"go": {Language: "go", Version: "1.26"}}
}, },
"an import form with no imports": func(m *seat.ModulesByModuleValue) { "an import form of another form": func(m *seat.ModulesByModuleValue) {
m.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", ImportForm: SourcePrefix2 + hex64("a")} m.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", Imports: []string{"p"}, ImportForm: "src1:" + hex64("a")}
}, },
} { } {
m := good m := good
@@ -68,8 +68,9 @@ func CheckModule(m seat.ModulesByModuleValue) error {
} }
} }
if in := m.Inputs2; in != nil { if in := m.Inputs2; in != nil {
if f := in.ImportForm; f != "" && (len(in.Imports) == 0 || !strings.HasPrefix(f, SourcePrefix2) || !keys.IsHex64(f[len(SourcePrefix2):])) { // An import form with no imports says a reported empty import set (design 47 H2 H-A-536, H-A-538).
return fmt.Errorf("meshcatalogclient: the kept import form %q is set only with imports, and is %s and 64 hex digits", f, SourcePrefix2) if f := in.ImportForm; f != "" && (!strings.HasPrefix(f, SourcePrefix2) || !keys.IsHex64(f[len(SourcePrefix2):])) {
return fmt.Errorf("meshcatalogclient: the kept import form %q is not %s and 64 hex digits", f, SourcePrefix2)
} }
for p, object := range in.Paths { for p, object := range in.Paths {
if !cleanInside(p) { if !cleanInside(p) {

Some files were not shown because too many files have changed in this diff Show More