Compare commits

..
Author SHA1 Message Date
mesh-tools 277c53067e Merge pull request 'Design 47 H1: proof 2, a two-module change along a dependency edge delivered by its pipeline (H §5 step 7)' (#273) from proof/47-H1-two-modules into main 2026-11-20 16:44:51 +00:00
mesh-tools 227f6e68ce Merge pull request 'Design 47 H1: a build with an unpinned package waits for its release (H-A-165)' (#277) from fix/47-H1-builder-waits-package into main 2026-11-20 16:41:47 +00:00
jschoubben 744204c5ab Builder: releases heard wake the package wait; its setting package-wait-minutes (H-A-165)
The process tells the builder each version-released it takes in and
gives it the newest release its record keeps, so an unpinned package's
step ask wakes on the event and pins the release; the wait's bound is
the setting package-wait-minutes (default 10), carried as a file under
the state dir like revision-wait-minutes.

Builds: design 47 H H-A-165, H-A-156, H-A-155
2026-11-20 17:37:25 +01:00
jschoubben 0f41b405ba Builder: a step ask naming a package with no pin waits for its release (H-A-165)
An entry keeps a mesh package with no released version unpinned
(H-A-161). Its step ask now waits, in the wait of H-A-155, for the
release of the module holding the package, heard or kept in the
builder's record of releases, and builds with that release as the pin;
past the bound the step fails naming the package and builds nothing.

Builds: design 47 H H-A-165, H-A-155, H-A-161
2026-11-20 17:37:25 +01:00
mesh-tools 20f0e9baaf Merge pull request 'Design 47 H1: a build waits for its revision and never builds without a version; a run's ask names no source (H-A-155, H-A-156, H-A-162)' (#276) from fix/47-H1-builder-waits-revision into main 2026-11-20 16:35:46 +00:00
mesh-tools 75c636a5ec Merge pull request 'Design 47 H1: the builder numbers nothing of its own; a published of other bytes leaves a kept entry (H-A-159)' (#275) from fix/47-H1-builder-versions-record into main 2026-11-20 16:32:12 +00:00
jschoubben 0cbabe9860 Runner and builder: a run's build step ask names no source; a held revision wakes the builder's wait (H-A-162)
A run on request copied its pipeline's source onto its build step ask,
so the builder waited for the run's candidate fingerprints in its
picture of the branch, where they never come, and failed every run past
the bound. The seat mesh-builds' contract leaves a run's source absent:
the runner now does. A revision the builder's view takes in whole that
changes no entry now also wakes a waiting ask, told by the catalog
client's new Held.

Builds: design 47 H H-A-162, H-A-155
2026-11-20 17:30:56 +01:00
jschoubben d2c9dc7de6 builder: builder_floor_again refuses; it asks no floor any more
With nothing numbered of the builder's own, the tool answered that a floor
would be asked at the next claim and looked again, doing nothing.

Builds: design 47 H H-A-159, G §369
2026-11-20 17:30:49 +01:00
jschoubben 53199f16ce Builder: the revision wait reads the picture and its setting revision-wait-minutes (H-A-155, H-A-156)
The process gives the builder its picture of each watched branch (the
source revision the branch's view holds) and the bound of a step ask's
wait for its revision, read from the setting revision-wait-minutes
(default 2) carried as a file under the state dir like
toolchain-wait-minutes.

Builds: design 47 H H-A-155, H-A-156, H-A-141
2026-11-20 17:27:37 +01:00
jschoubben 256eb34a0d Builder: a build step ask waits for its revision before it builds (H-A-155)
A step ask reached the builder before its picture of main's catalog
revisions held the revision the pipeline builds; the fingerprint was
built as no first branch's build, reserved no version, and the step
failed on builder_reserve_done's words. The ask now waits, woken by each
entry the picture takes in, until the picture holds its source revision
and the asked entry from its branch; past the bound it fails naming the
revision and builds nothing.

Builds: design 47 H H-A-155, H-A-141
2026-11-20 17:27:37 +01:00
jschoubben a47c8e7922 builder: number nothing of its own; the reservation numbers
Every look numbered one more patch in the state versions (claims carry no
source revision since H-A-48): nodeengine 0.1.5 to 0.1.36, beside the
reservation's numbers.

Builds: design 47 H H-A-159, G §348, §349, §369
2026-11-20 17:24:48 +01:00
jschoubben 16f9ad2950 builder: a published of other bytes leaves a kept versions entry as it is
The reservation's published of nodeengine 0.1.4 (9724da7a) was taken into the
state versions' entry 0.1.4, numbered for an older fingerprint, which turned
published and kept the old digest c0ef9a3d.

Builds: design 47 H H-A-159, G §369, A-415; ADR 0605 §4
2026-11-20 17:23:19 +01:00
mesh-tools b1f25f91d5 Merge pull request 'Design 47 H1: validate reads the base the take-in names on the catalog revision; the indexer's restart tests wait for the bus (H-A-151, H-A-154, H §743)' (#274) from fix/47-H1-indexer-toolchains-test into main 2026-11-20 16:09:50 +00:00
jschoubben d281faeeb7 mesh-delivery-assigner: the validate test judges a revision whose base is below its number minus one
Every revision the validate test judged with a base had it at its number minus one, so the test
passed with the case before read as the number before (review round 1). Revision 12 now names base
7 with 8 to 11 never kept: it ends manifest-refused against base 7's manifests, and could not run
when the case before is read as the number minus one. No test added.

Builds: design 47 H-A-154 (hq design/47-H1-answers-59 01842bbe), H-A-151
2026-11-20 17:08:23 +01:00
jschoubben e312999843 Design 47 H1: proof 2, a two-module change along a dependency edge delivered by its pipeline (H §5 step 7) 2026-11-20 17:06:04 +01:00
jschoubben 5dba7fe68b mesh-catalog's revision names its base; validate's case before reads it, not the number before
A take-in that moves nothing keeps no revision for its source number, so validate's case before,
read as the step's revision minus one, named a revision never kept and could not run. The take-in
now writes, on the catalog revision it keeps, the field base: the newest kept revision below it,
the one it pins for its pipeline, in the same write; absent on the branch's first take-in. The
assigner's validate reads the base from the revision it already asks for; where the revision names
none the case before is empty and its end says so, never a could-not-run.

- mesh-delivery-contracts: the seat mesh-catalog's CatalogRevision gains base (schema, fixture,
  generated Go and TypeScript by seatgen).
- mesh-delivery-indexer: keepBranchEntries names the base it pins; the pin test's rows check it.
- mesh-delivery-assigner: before reads the base; the validate test asks a revision with none, and
  both stand-ins name the base as the take-in does.

Builds: design 47 H-A-151, H-A-154 (hq design/47-H1-answers-59 01842bbe), H-A-147, H-A-108 (3), design 47 H §743
2026-11-20 17:00:55 +01:00
mesh-tools f0f28c56a4 Merge pull request 'Design 47 H1: an assignment no watched branch lists is left out of a machine's composition, said and raised as a finding (H-A-148, H-A-149, H-A-152, H-A-153)' (#272) from fix/47-H1-unlisted-assignment-left-out into main 2026-11-20 15:54:36 +00:00
jschoubben 20a7bd0f3c mesh-delivery-indexer: the restart tests wait for the take-in's end and the bus's close
TestIndexerCountsOnlyThePlacedBuildNodesToolchains failed on the build node under load
(pipeline main.18) in two ways, both of the test, not of the indexer's count of the
placed build nodes' toolchains:

- it restarted the indexer as soon as the module was written, before its take-in
  ended: the stop cancelled the take-in, its source-moved stayed unacknowledged, and
  the branch's durable (one message at a time) held the next one behind it for its
  acknowledgement wait, past the test's 20 s bound. Each restart now waits for the
  source-moved's acknowledgement; TestIndexerWhole's restart the same way.
- a source-moved said right after a restart could reach the stopped program's pull,
  still counted until the bus closed its connection. restart now returns only once
  the bus has closed every connection of the stopped program, heard on the system
  account's disconnect events, with no sleep.

Under load (8 runs side by side, GOMAXPROCS=1) the test failed 5 of 80 runs before,
2 of 240 with the first change alone, and 0 of 600 with both; TestIndexerWhole 0 of 600.
No test added.

Builds: design 47 H §743
2026-11-20 16:54:26 +01:00
jschoubben 0b1ce08985 assigner: one set of unlisted assignments, carried on the run (H-A-152, H-A-153)
The leaving-out took every assigned module the case's manifests lacked,
while the judgement said only those the watched branches' newest
revisions list nowhere, read again at judgement time. Now the set is read
once from the newest revisions when the run starts, written on the run,
and used for the leaving-out, the finding and every step's judgement and
the resume. The candidate never enters it: a module the change drops
while still assigned stays in and fails the composition as its own
fault. While no newest revision is followed nothing is left out.

Builds: design 47 H H-A-152, H-A-153
2026-11-20 16:51:28 +01:00
jschoubben f053e3b041 mesh-wants: a composition run carries its unlisted assignments (H-A-153)
The judgement of every step reading a run, and the resume after a
restart, read only the stored run; the set of assignments left out is
written there when the run starts, so it is not kept in a step's memory.

Builds: design 47 H H-A-153
2026-11-20 16:47:57 +01:00
jschoubben d428650ce4 assigner: raise assignment-unlisted where a step leaves one out, clear it in the pass (H-A-149)
A stale assignment left out of a machine's composition is now a finding the
condition keeper carries: kind assignment-unlisted, scope delivery, id
<node>.<module>, a warning, raised by the composition step that leaves it
out. The pass over the assignments clears it when the assignment is gone or a
watched branch of the module lists it again, so the clear never waits for the
next step on that machine.

Builds: design 47 H H-A-149, H-A-148
2026-11-20 16:31:50 +01:00
mesh-tools 351eda0867 Merge pull request 'indexer: a take-in pins the branch's previous revision for its pipeline, so validate's base stays (H-A-147)' (#271) from fix/47-H1-validate-previous-revision into main 2026-11-20 15:31:05 +00:00
jschoubben 5e3d92ae33 assigner: leave a stale assignment out of a machine's composition (H-A-148)
The retired checker's assignment on the control-node made every composition
there refuse "nothing provides", so every composition step on that machine
ended could not run. A module assigned to a machine that the case's manifests
do not hold (no watched branch lists it) is now left out of the case's
assignments as well, said in the journal and at the judgement as unlisted, and
the machine is judged on what remains: a stale assignment is a fault of the
assignments, not of the change judged.

Builds: design 47 H H-A-148, H-A-143; ADR 0578 §2
2026-11-20 16:29:16 +01:00
jschoubben e5e5c50e67 mesh-delivery-indexer: a take-in pins the branch's previous revision for its pipeline, so validate's base stays
The pin judge removed the branch's previous revision in the very write that took the next one in
(pipelines main.13 and main.15 on 2026-11-20), so the validate step's case before could not be read
and the composition was never asked. The take-in now pins the newest revision it kept before its
write under the same pipeline record as its own, and the pipeline's end frees the record on every
key it pins; a take-in with no revision before it pins only its own and says so.

Builds: H-A-147 (hq design/47-H1-answers-59 310f8955ba16a1ca8ae9661d8196cab16e3d9597), design 47 H §743, §749, H-A-108 (3)
2026-11-20 16:27:21 +01:00
mesh-tools 8167d825ed Merge pull request 'mesh-grants: the marks subtest calls on the caller's granted token and waits for its refusals; the test's nats_streams stand-in skips a consumer gone' (#270) from fix/47-H1-grants-marks-test into main 2026-11-20 15:19:12 +00:00
jschoubben ac95e5628c mesh-grants: the test's stand-in nats_streams skips a consumer gone between its listing and its read
Under load (8 copies side by side) TestTheGrantsPartWhole panicked at
integration_test.go:151 at abb7cfcf too: st.Consumer's error was dropped
and a consumer deleted after ConsumerNames listed it gave a nil one.

Builds: design 47 H §746 (the pipeline's integration step)
2026-11-20 16:11:14 +01:00
jschoubben bed9b61d5a mesh-grants: the marks subtest calls on the caller's granted token and waits for its refusals
The subtest "a runtime denied the marks is delivered no call on a marked
subject" published the caller-named call on mesh.mod.shell.call.execute.asker~a,
a token the composer never grants (buscompose.CallerToken gives a~asker
for the user a.asker), so the server refused it every time; the test
passed only because it read the refusals with a non-blocking select
right after Flush, before the client's error callback had run. Under
load the callback won the race and the pipeline's integration step
failed (main.12, 15:50). The call now uses CallerToken, and a probe on
another caller's token is published last: the server refuses in order,
so waiting for the probe's refusal waits on every refusal asserted.

Builds: design 47 H §746 (the pipeline's integration step), G A-203 (AM-D4)
2026-11-20 16:09:35 +01:00
mesh-tools 67ef449230 Merge pull request 'mesh-grants: bring a held kept stream to its definition's source filter (H-A-145)' (#269) from fix/47-H1-kept-stream-source-filter into main 2026-11-20 14:47:59 +00:00
mesh-tools 8a52b6f801 Merge pull request 'forge bridge: adopt only an added branch; its integration tests wait on what they assert' (#268) from fix/47-H1-forge-bridge-integration into main 2026-11-20 14:46:50 +00:00
jschoubben 380d4781e6 mesh-grants: bring a held kept stream to its definition's source filter
The kept stream of the runner's pipeline-ended was made at G's
definition, sourced by a three-part subject; H1 moved the event to
<branch>.<source>, so the stream took nothing in since 08:13 and the
assigner, which hears a kept event from its kept stream, heard no end.
createKept left every held kept stream as it was. It now brings a held
one's source filter from the events stream to the definition's in place
(a stream update, its messages and other settings kept, never made
again) and says the held and the composed filter in the journal and the
pass; the same holds for pipeline-started and wait-held.

Builds: design 47 H H-A-145 (hq design/47-H1-answers-59 0787704b), §746
2026-11-20 15:42:24 +01:00
jschoubben 7534bf5c07 forge bridge: adopt only an added branch; its integration tests wait on what they assert
Pipeline main.8 failed TestBridgeSaysOneHeadMovedPerMove and TestBridgePerformsWhatIsOwedOnce on
shanks; both fail the same way at 403fb306, before the catalog client change, under load.

- The bridge read every head again, start true, whenever the registrations' first view said its
  values after the start had begun, so a head moved just after the start was said as a start.
  Only a registration adding a watched branch is adopted now (Watched.Set says so), decided under
  one lock with the start's read.
- The head-moved test moved the head before the restart's read was answered, and read the state
  heads before the bridge wrote it; it now waits for the stand-in's answer and watches heads.
- The owed test stopped the bridge while an outcome's publish was on its way (heard again after
  the start), and an act said while the bridge stops can be handed to the stopped bridge's pull,
  which the bus hands again only after the consumer's acknowledgement wait (30 s) past the
  test's 20 s bound. It now hears the bridge's acknowledgements before the stop and waits the
  consumer's acknowledgement wait for the act said meanwhile.

Builds: design 47 H §739; design 47 G §532; design 47 H-A-48
2026-11-20 15:41:10 +01:00
mesh-tools 08fe40f233 Merge pull request 'assigner: a machine's composition across the watched branches (H-A-143, H-A-144)' (#267) from fix/47-H1-compose-across-branches into main 2026-11-20 14:38:28 +00:00
jschoubben 27e96a2a1b assigner: say an unlisted module on every path; no registration, no branches (H-A-144)
Review round 1: an unlisted module was lost where the composer blamed a module.
It is now said in the failed or could-not-run words where one is set, else as a
warning. Once registrations are held, a module none names has no watched
branches and is unlisted, never composed from the branches the client follows;
before the first registrations the gate's source's branches stand in, in its
order. A module is judged unlisted by its own watched branches.

Builds: design 47 H H-A-143, H-A-144, G §532
2026-11-20 15:35:59 +01:00
jschoubben f98d5ec748 assigner: compose a machine across every watched branch (H-A-143)
The composition step judged a machine at the step's one branch revision, so an
app registered on another watched branch was missing and the machine failed
"nothing provides", ending every mover there "could not run". Each module's
entry now comes from the newest revision of the first of its watched branches,
in its registration's order, that lists it; the candidate's revision replaces
its branch's newest for the modules it moves. A module assigned to the machine
that no watched branch lists is said in the machine's reason.

Builds: design 47 H H-A-143, G §532
2026-11-20 15:28:29 +01:00
mesh-tools abb7cfcf5d Merge pull request 'meshcatalogclient: a revision below the held one asks the first view again (H-A-141)' (#266) from fix/47-H1-catalog-client-numbering-restart into main 2026-11-20 14:09:37 +00:00
jschoubben 3956c0cf94 meshcatalogclient: a revision below the held one asks the first view again
A reader whose picture held the earlier model's revision 528 skipped
revisions 1 to 7 of the new numbering in silence: the builder built
every pipeline step as a candidate's, unversioned, so nothing was
released and no want moved. An event below the held revision is now
the state made again: said with both revisions, the view's made time
moved on (so the follower forgets the old numbering's revisions heard
and is not left behind for good), and the first view asked again. An
event equal to the held revision is still dropped.

Builds: design 47 H H-A-141 (hq design/47-H1-answers-59 3d722934), §750, §754
2026-11-20 15:05:06 +01:00
mesh-tools 403fb3068b Merge pull request 'The indexer makes its own per-branch durables and drops the earlier model's revisions at a take-in (design 47 H, H-A-134, H-A-135)' (#265) from fix/47-H1-indexer-durables into main 2026-11-20 11:21:50 +00:00
jschoubben e54bf7f346 indexer: a branch's durable it makes waits 30 s, delivers 5 times, starts from now
As the grants part gives a module's consumer on a seat event's stream kept by age:
without a start from now a made durable would replay every past source-moved of the
branch past the start's guard; the current revision is read at the start already.

Builds: design 47 H §743, H-A-134 (hq 8d30cc42), H-A-129, H-A-130

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 12:19:50 +01:00
jschoubben f95a164941 indexer: drop the earlier model's trunk and branch revisions at a take-in
catalog-revisions kept trunk.<n> and branch.<branch>.<n> objects beside the
branch-keyed revisions, the newest trunk one marked current, so a reader heard
revision 528 while its picture held 1. A branch's take-in now drops every such
object no record pins, says the count in the journal, and the revisions tool marks
each branch's newest revision current.

Builds: design 47 H §743, H-A-135

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 12:12:23 +01:00
jschoubben 0cf419619e indexer: make a watched branch's source-moved durable when the bus holds none
The grants part composes no per-branch durable on the source-moved stream, so the
indexer never heard a source revision after its start. Its bind now makes the
durable itself, as a module's seat-event consumer is made (SeatEventConsumerConfig,
named <node>_<indexer>_<branch>, filtered to the branch, one message at a time),
and binds an existing one as it stands.

Builds: design 47 H §743, H-A-134

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 12:10:46 +01:00
mesh-tools 8b6f6b22d4 Merge pull request 'The indexer reads a branch's source by the verb when its consumer is not bound (design 47 H, H-A-129, H-A-130)' (#264) from fix/47-H1-indexer-bootstrap into main 2026-11-20 09:46:08 +00:00
jschoubben 9cddb5921a indexer: take a watched branch's source revision in from the gate's source when its consumer cannot be bound
At a clean state the grants part makes the per-branch consumers of source-moved only from the modules view, which the
indexer answers only after its first take-in, so nothing ever took the trunk in. At its start, and again at each
failed bind, the indexer now reads the branch's current source revision through mesh-delivery.source and takes it in
as a heard source-moved of it would, when its view keeps no revision of the branch at or above it: start true exactly
when it keeps none, every repository the answer names a head. No timer; binding on registration-changed is unchanged.

Builds: design 47 H §743, §768, H-A-129, H-A-130

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 10:39:45 +01:00
mesh-tools 842da1be85 Merge pull request 'Design 47 H1: the one chain (take-in, forge bridge, pipeline runner, assigner, teller, view, watchman, grants; checker gone)' (#263) from feat/47-H1 into main 2026-11-20 07:15:12 +00:00
jschoubben 3090a80a09 indexer: indexer_pin_drop's all form drops every pin for the clean state
Review round 1, H-A-121 (2): beside the one-item form, all true drops
every pin of the state pins, each recorded through mesh-hand-acts and
asked of the indexer as the one-item form is; it answers the count
dropped and the pipelines the pins named.

Builds: design 47 H §765, H-A-121, H-A-124

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:55:59 +01:00
jschoubben 03c0b627ad assigner: assigner_want_drop's all form drops every want for the clean state
Review round 1, H-A-121 (2): beside the one-item form, all true drops
every want key, held or not, and every value of an earlier form the
decoder refuses, each act recorded through mesh-hand-acts first; it
answers what it dropped, counted per kind (held, current, undecodable).

Builds: design 47 H §765, H-A-121, H-A-123

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:54:39 +01:00
jschoubben af5d5f87dd forge bridge: the stream forge keeps head-moved 7 days
Review round 1, must 6: the stream's definition names its keep, as the
manifest template states a stream's age (max-age-days).

Builds: design 47 H §739, H-A-23

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:51:33 +01:00
jschoubben fbd75dfac4 indexer: what nothing reads goes
packageEntries, manifestBytes, writtenModules, WriteHeard, heldOldSections, keepOldSections,
the overlay's written and changed, moduleOfDir with moduleAt, EncodeSeriesPackage,
InputDigest, HoldSeats and the barBlock shape's functions are referenced by no file of the
repository; with HoldSeats gone the seat list's lock is a plain mutex WithSeats takes.
barShows and barOption stay: a judge test reads them.

Builds: design 47 H §764; lead answer H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:32:16 +01:00
jschoubben 40bd5cf69d steprun: the pull-order test asserts the kinds' turns, as the code has since 2026-11-15
TestPullOrderAndCapacityOnTheBus still asserted deliveries first, red since 773f89e9 made
the build seats' queue kinds take turns (not since 83d45421: it fails at 83d45421^ too).
It now asserts a delivery, then the check in its turn, then the other delivery; it fails
on a pull that takes deliveries first.

Builds: design 47 H H-A-41, H-A-117, H-A-120; G A-440

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:30:42 +01:00
jschoubben a94b275a9c I-114 fix: a state held not there yet holds nothing to take in first
Before the state held is bound, hearing a source-moved read it to hold the event behind
earlier ones, failed and left every message unacknowledged, so nothing was taken in (two of
the indexer's integration tests, which make no held state). A state not there yet holds
nothing: the event is taken in; holding it still needs the state.

Builds: design 47 H H-A-114, H-A-118
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:24:20 +01:00
jschoubben 12b48debe9 T-119: the teller says one widening per mover; record-opened is no longer heard
The teller reads pipeline-ended's H1 form, saying each mover's widening once for its module,
watched branch and commit; its hearing of record-opened, whose forge-made record H §763
retires, goes with its consume in the manifest.

Builds: design 47 H H-A-119, H-A-72, H-A-51, §763
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:18:13 +01:00
jschoubben 05b91a6281 C-R6: pipeline-ended names each mover's commit and widens
The seat mesh-pipeline-runner's MoverEnded gains commit and widens (regenerated, with a
fixture row), and the runner writes them from its pipeline value when it says
pipeline-ended, so the teller says a widening from the event alone.

Builds: design 47 H H-A-119, H-A-72, H-A-51
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:18:13 +01:00
jschoubben ecc87a6510 I-114: a held take-in is acknowledged and kept whole, in order, in the state held
A source-moved the indexer cannot take in is written into the state held, the event whole
(call, heads, start beside branch, source, why, since), and acknowledged once written; a later
source-moved of a held branch is held behind it, and the branch's key keeps them in order.
The indexer takes them in again from that state alone, in their order, on its own room and
at its start; one neither taken in nor written stays unacknowledged. The whole test's held
case reads the new form and that nothing is left unacknowledged.

Builds: design 47 H §744, H-A-114, H-A-118
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:15:02 +01:00
jschoubben 76b2e8dc7d A-60: the assigner asks an unreached entry again to entry-asks, then writes entry-unanswered
The passer's catalog entries are the followed branches' own, so each catalog-revision asks
again an entry whose ask failed to reach the holder, and so does each reopening of the
assigner's link to the bus; the manifest's setting entry-asks (default 5) bounds it, and past
it the assigner's finding writer writes entry-unanswered (and entry-not-found) through the
entries client.

Builds: design 47 H H-A-60
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:10:24 +01:00
jschoubben 6b50f3eb9d V1 join: indexer_pending has one form; the take-in package's old answer goes
The view's tools already read indexer_pending's {held: [{branch, source, why, since}]} through
view.DecodeHeldTakeIns at the joined base; the take-in package's earlier PendingAnswer,
PendingWait and DecodePendingAnswer, read by nothing since, go with their test.

Builds: design 47 H H-A-102, H-A-97
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:05:13 +01:00
jschoubben c9f0beedd1 X1 join: the checker's generated packages, requires and askers go
The seat mesh-delivery-checker's generated Go seat, client and TypeScript package go from
mesh-delivery-contracts (and their entries in its manifest), with the old copies under
contracts/go; the indexer, the forge bridge and the assigner require them no more, and the
assigner judges with its own internal/assignment verdict constants. The git, node-build-go
and node-build-node fixtures, the buildstep and steprun tests and the indexer's and
assigner's whole tests name the seat mesh-wants (the asker of every check-kind run in H1)
or the runner where they named the checker; the indexer's unused CheckerModule and the
judge's stream exemption for the checker go. The step kinds check and recheck stay with
their queues (H-A-117).

Builds: design 47 H H-A-57, H-A-117
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:04:11 +01:00
jschoubben 5f4eb03fcf Join: the assigner's composition-run test reads no case verdicts
The assigner branch was built before SDK-C took Case.Verdicts out of the composer's request;
its test still read the field, so the joined line did not compile.

Builds: design 47 H H-A-112
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 05:04:11 +01:00
jschoubben 20bbf346dc A13: the whole test follows the newest passed version, tier by tier
The assigner's whole tests no longer assume wants follow the trunk's
fingerprint: a runner's pipeline-ended names the movers and versions, the
wants are written tier by tier on running, and pipeline-wanted says running
at the end. Test 113's cases: a provider and its consumer in tiers, the
acting part's build and the old holds ignored, a failed pipeline's version
and an older end heard late writing nothing, a placement's build reverting
the want, tier-late after tier-bound with no later tier written, and a node
not stating want:version held awaiting its hand placement. Test 117's cases
run the step validate whole: a refused manifest, a pass and a cycle. The
first views answer every account (no callers), and tier-bound's unit is a
variable the whole test shortens.

Builds: design 47 H §774, §750, §751, §772, §745, §752; acceptance tests 113, 117; lead answers H-A-10, H-A-37, H-A-40, H-A-41, H-A-56, H-A-73, H-A-75, H-A-99, H-A-108

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 0bb24f91a8 H-A-112: the composition step's case carries no verdicts
The composer's Case.Verdicts goes (its one writer was the checker); the
validate step judges the manifests before the composition step, so caseOf
answers the manifests and none words alone.

Builds: design 47 H §745; lead answers H-A-112, H-A-108

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 70ccb470a7 Rebase onto C1d: the assigner reads no source stamp of a catalog entry
The seat mesh-catalog's module value and entry inputs lose src and fp-src
(C1d), so a trunk entry's release is the version-released whose parts are
what its build.ended made, the one way left of the two the assigner had.

Builds: design 47 H §764; lead answer H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben e4d51a47f7 A10: the step validate, one run per take-in revision before the composition
The assigner takes the seat mesh-wants' step validate beside the composition
step. Every mover's validate step of one take-in reads one run, the key
<pipeline>.validate of composition-runs with no machine, taken up at the
start like the composer's runs: a cycle the revision's entries make
(graph.RefusedCycle) ends it at once; else the manifest validator built from
the revision's entry of the module holding mesh-catalog runs on the Go build
seat, its input kept and served on mesh-wants' input, over the revision's
manifests and the branch's previous revision's. The step ends failed cycle,
failed manifest-refused naming every problem the revision causes, or passed.

Builds: design 47 H §745; H-A-34, H-A-51, H-A-108

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 1ede9a5f11 H-A-104: the assigner keeps each node's engine words in its own state engine-reads
The words of each node-engine's manifest-reads-changed are written into the
assigner's state engine-reads, key the node, value {words, at}, before the
event is acknowledged, and read back from the state's watch at the start, so
a restart loses no node's words. The verb manifest-reads is no longer asked:
the keeper's asks, the unanswered-call finding and the node-record fallback go,
with the invoke in module.json. assigner_engine_reads lists the state.

Builds: design 47 H §772; H-A-104 (1), H-A-45

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 79322692c6 A8: a placement's build names the want's version
The pass reads each node's placement before the rule: a placement naming a
build has its want name that build, by the version released at it (the kept
end's when it is that build, else the release whose parts the build made),
with no pipeline and no rank; with no released version known no want is
written, said once. A placement's build is no longer made a held put:
placementPuts and its test go, and a placement naming no build any more
gives the node back to the rule.

Builds: design 47 H §750, H-A-5, H-A-37, H-A-39, H-A-99

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 037cb74640 A7: one pipeline's wants are written tier by tier
On a passed pipeline-ended the assigner keeps the tier progress of the
pipeline in its state written (`pipeline.<branch>.<source>`, {tier, since,
movers}) and writes the wants of the movers of the current tier only; once
each of them runs at its fingerprint on every present placing machine, the
next tier's wants are written in the same pass, and after the last tier
pipeline-wanted says running and the progress goes. A tier counts placed
movers; a machine away is not waited for; a mover a later pipeline moved
counts as run. A tier past the setting tier-bound (default 30 minutes, a
config file the manifest declares) raises the finding tier-late (scope
delivery, id the pipeline) naming the movers and machines not running, says
pipeline-wanted tier-late and writes no later tier; the finding clears when
the late movers run or a later pipeline moves them. One timer wakes the pass
at the earliest deadline. wanted names the pipeline its want follows.

Builds: design 47 H §751, H-A-10, H-A-40, H-A-56, H-A-72 (6), H-A-75

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 46f1a54189 A6: the whole test of the composition runs says a superseded run's end in the new form
Its pipeline-ended names a source and its mover, as the runner's client reads it.

Builds: design 47 H §746, §750

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben bdbfa12aa1 A9: a node whose node-engine reads no want by version is held, awaiting its hand placement
The want of a node whose node-engine does not state the word want:version of
the seat node-engine, as the engine reads keeper holds it from
manifest-reads-changed, is written with hold and the words
awaits-hand-placement; once the engine states the word, the next pass writes
the want unheld.

Builds: design 47 H §772; H-A-45, H-A-73

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 4923d22ac6 A12: assigner_want_drop drops one want by hand, recorded first
The tool takes node, module and why: the act is recorded through the seat
mesh-hand-acts, then the key want.<node>.<module> is deleted from the state
wants; the next pass writes the want of the new form. Refused with no want
under the key, no why, no proven caller, or when the act is not recorded.

Builds: design 47 H §765; H-A-58

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:45 +01:00
jschoubben 4613300bcd A5, A6: a want names the newest version released whose pipeline passed, held for nothing else
The want rule is written again (internal/assign Wants): for every node the
module is assigned to, the want names the version, the pipeline and the
mover's rank kept for the module on the placement's branch from the runner's
pipeline-ended; a put owns its node's want as before. The state written keeps
per module and branch the newest passed version, by compare-and-set on a
newer version: a failed pipeline, a mover whose required step failed, an
older version, the same one again and a run on request keep nothing; a run's
end drops its candidate graph (H-A-58). group-ended is no longer heard.

The old holds go with their code, findings, asks and tests: the canary and
step, every provider healthy, the grant, the composition and reader
capabilities, the provisions (the provisioner's read, its findings), the served
verbs, the bus state, rule 2 (the held fingerprint, its hold and restore asks,
its lift and conditions), the neither list, the network hold and A-428's
exceptions (H-A-55). The record yes stays as the node-engine's have asks it.
A want names no composition, so the backup ask is bound to the build.

The callers API's call sites go (H-A-66): the seat list's callers, the
first-view callers lists in the manifest, the step asker judgement, the
enrolment caller read locally. The assigner's revision pins go whole with the
gate's pin events (H-A-86): a revision not current is removed when one ceases
to be current and at the start.

Builds: design 47 H §750, §752, §764, §765 (assigner part); H-A-37, H-A-55, H-A-58, H-A-66, H-A-86

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:44 +01:00
jschoubben 1cf2ea46ff A11: a composition step's progress names the asker its step run carries
With no callers list on the seat mesh-wants, the asker a step's progress names is
the one the runner writes on the StepRun it asks (C-W2), mesh-pipeline-runner.

Builds: design 47 H §752 (consequence), G §496; H-A-41, H-A-88

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:57:44 +01:00
jschoubben 2a93cbcd9b R17: the queue's whole test against the bus
The runner started whole with pipelines-at-once 1 and pipelines-waiting-cap 1: a second take-in
waits, saying wait-held, and is placed with wait-ended on the first's end; a newer waiting take-in
takes its shared movers out of an older waiting one, which ends superseded; a start over the cap
waits and raises queue-full, cleared on the count; a cancel places the next; a pipeline on its
approval alone gives up its place and, answered while it still runs, is keyed running at once; a
placing the bus refuses raises pipelines-stalled, cleared when the next start places the waiting
from the runner's own state, which starts no pipeline of its own. The tools runner_rerun,
runner_accept and runner_ask_again are shown to take the mover's module.

Builds: design 47 H §748, §774; acceptance test 112 (the runner's half); lead answers H-A-14, H-A-36, H-A-52, H-A-53, H-A-96, H-A-101, H-A-106, H-A-107

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 0548dc8f80 R13: a mover whose dependency was superseded out says so in its build's why
A waiting pipeline keeps in superseded (C-R5) the modules a newer waiting pipeline of its branch
took out of it, written with its movers by compare-and-set; at its placing each mover building on
one of them (an edge of a kind its build waits on) has its build step's why say that dependency was
taken out and that it builds against the newest published package.

Builds: design 47 H §748; lead answers H-A-53, H-A-107

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 213668df49 R14: the queue's tools, runner_waiting and runner_place over the verb place
The seat verb place places a waiting pipeline ahead of its turn, written in the hand-act log first:
its running key now, over the bound, its waiting key deleted, its steps placed as at its turn with
wait-ended; a pipeline not waiting is refused. The tool runner_place asks it with the pipeline and
why; runner_waiting lists the waiting pipelines, lowest sequence first, from the state queue. Both
are in the manifest's tools.

Builds: design 47 H §748; lead answer H-A-53

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben bb930de377 R12: the queue's approval wait, stall and cap
A pipeline whose every step not ended is an approval asked of the operator leaves the bound: its
running key goes and the next waiting is placed; answered and still running, it is keyed running
at once, over the bound. After every placing, pipelines waiting with none running raise the finding
pipelines-stalled naming the first waiting, cleared once one runs. A start beyond
pipelines-waiting-cap is an ordinary waiting pipeline and raises queue-full naming it, cleared when
an end brings the waiting back to the cap. Both findings are the scope delivery's, the kind as id,
warnings with no owner.

Builds: design 47 H §748; lead answers H-A-14, H-A-36, H-A-52, H-A-106

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben bbdd1741fa R13: a newer waiting pipeline supersedes the older one's movers
When a pipeline is written waiting, each older waiting pipeline of its branch loses the movers the
newer one also moves (read from the queue's waiting keys and each pipeline by its key); one left
with no mover ends superseded, its waiting key deleted, saying wait-ended (how superseded) and its
pipeline-ended. A running pipeline is never touched and runs to its end. The queue test's fixture
is shared, its take-ins moving distinct modules.

Not built: H-A-53's why of a mover whose dependency was superseded out (asked of the lead: no field
keeps the movers that left).

Builds: design 47 H §748; ADR 0682 §7; lead answer H-A-53

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 63bb53bb6b R11: at most pipelines-at-once pipelines run; the others wait in order
The runner's settings pipelines-at-once (default 1, from 1 to 8) and pipelines-waiting-cap (default
64) are written to files by the manifest and read at the start; its state queue holds queue.next,
waiting.<sequence> and running.<pipeline>. A start (a take-in's, a publish's, a hand start's, a run
on request's) judged against the running keys alone either runs, its running key written after its
pipeline, or is written waiting under the next sequence, its waiting key first, with no step asked,
saying pipeline-started and wait-held step pipeline on pipelines-at-once. Every end, a cancel's too,
deletes the running key and places the lowest sequence, which says wait-ended and has its steps
placed (a run's from its candidate's newest revision). At the start a running key whose pipeline
runs no more is deleted and the queue placed. The test runs' whole test sets pipelines-at-once 8, as
its candidates run side by side.

Builds: design 47 H §748; lead answers H-A-14, H-A-36, H-A-52, H-A-53, H-A-60, H-A-72, H-A-96

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben cf703c2a7b H-A-101: the hand verbs name the mover's module; a step not asked says its own end
rerun, accept and ask-again take the mover's module beside the pipeline and step (C-R4): a call
naming none is taken as the pipeline's one mover and refused on a pipeline of several, and a module
the pipeline does not move is refused; the tools runner_rerun, runner_accept and runner_ask_again
pass it. A step of a mover whose dependency did not build, placed not asked, now says its own
step-ended naming the dependency, so nothing ends silently.

Builds: design 47 H §746, §748; lead answer H-A-101

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 1bd410522e R4 correction: a run on request is refused when its branch has no source revision yet
A run's pipeline puts in source the newest source revision of its branch (H-A-85); a branch whose
view holds none yet is refused, naming it, and nothing is written, never a pipeline of source 0.

Builds: design 47 H §746; lead answer H-A-85, H-A-83

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 79e4688744 R16: a take-in.taken of the old form is refused by the strict decode
The runner's take-in handler decodes take-in.taken strictly by the seat's contract: an event
missing a field its new form requires (branch, source, call) is refused, said in one journal line
naming the subject and what it lacks, and ended. The cancel reads no old pipeline (they are
dropped at the clean state). Unit tests 84 to 85.

Builds: design 47 H §765; lead answers H-A-58, H-A-98

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben c9fd571e8e R15: pipeline-failed is one finding per failing mover
The finding pipeline-failed has scope delivery and id <module>.<branch>, one per mover whose
required step failed or could not run, naming the pipeline and the steps, owned by the commit's
author as before; that module's next passed pipeline on that branch clears it. Unit tests 84 to
84 (the newer-revision test replaced).

Builds: design 47 H §770; lead answers H-A-19, H-A-59

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 8da18c37c5 R10: a publish starts only what its source's pipeline does not move
A package-published is heard in the running pipeline of the source revision that published it,
where its dependents wait (R7); every module the catalog half holds a kind-1 edge from the
package into that this pipeline does not move (a publish again of an older build, a dependent it
does not move) is a mover of one pipeline keyed <branch>.<source>.published.<package>.<version>,
at the publishing source's catalog revision and call. The dependents come from the edges the
runner holds: the runner asks outdated no more (its invoke leaves the manifest). A publish heard
before its branch's half is held is heard again once it is; the durable consumer delivers one
heard after a stop, the key written once. Unit tests 83 to 84.

Builds: design 47 H §747; lead answers H-A-19, H-A-52

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben c3d17f6b5a R7: a mover's build waits for its dependencies inside the pipeline
A mover with a kind-1 edge from another mover (a package) is placed once that mover's
package-published of the pipeline's branch and source is heard, written into the publishing
mover's published by compare-and-set; one with a kind-3 edge (a build module, an image base)
once that mover's build step passed, heard as the runner's own step end; toolchain edges first.
A publish of a mover of the running pipeline of its source starts nothing and asks no outdated.
A mover whose dependency's build ended without passing is placed with every step not asked.
Unit tests 82 to 83.

Builds: design 47 H §746 (the build order); lead answers H-A-51, H-A-83 (2), H-A-84

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben e5a79db912 R9: validate comes before composition, one run per pipeline
Each mover gets a validate step on the seat mesh-wants before its composition, its status from
the policy; one ask per pipeline that every mover's validate step reads (a mover placed later
reads it, its result too). A mover's composition waits until validate ends: asked once it
passed, ended not asked when it did not, so a manifest the validator refuses is never composed.
The step runs name the runner's seat as their asker. Unit tests 81 to 82.

Builds: design 47 H §745 (the runner's order); lead answers H-A-51, H-A-88

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben f9d403ffea R8: a mover's released version is heard from version-released
The runner consumes mesh-catalog.version-released and writes its version into the mover of that
module in the pipeline of the source revision built, on the branch the version was released for
(the registration's first watched branch), by compare-and-set, so pipeline-ended names the version
released. Unit tests 80 to 81.

Builds: design 47 H §746 (the released version per mover); lead answers H-A-52, H-A-62

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben a755925024 R4, R5, R6, R8: one take-in is one pipeline, its movers placed, ended and said per source revision
A take-in.taken with entries starts one pipeline keyed <branch>.<source> by compare-and-set, its
movers the entries; each mover's steps are placed from its own registration and entry, each step
and ask id naming its mover; a step end is matched to its mover's commit and fingerprint; the
pipeline passes when every mover's required steps passed, a required "nothing to run" counting
as passed. The movers get tiers from the delivery edges (kinds 2, 4, 5, 6; a cycle one tier,
said). pipeline-started and pipeline-ended are said on <branch>.<source>, the end once with per
mover its fingerprint, version, steps and tier, in tier order; waits on <branch>.<source>; step
events on <module>.<branch>.<commit>; no group-ended. Approval is one step per mover. A run on
request is one pipeline keyed <branch>.run.<id>, its source the branch's newest, members of one
branch only. A running pipeline is superseded no more. A composition step names the runner as
its asker. The seat's verb place is served, refusing every pipeline until the queue (R11, R14).
The seat list part takes no callers (H-A-66). Unit tests 77 to 80, integration 3.

Builds: design 47 H §746, §747 (run, start, a publish's key), §748 (a running pipeline runs to its end), §764 (group-ended, the key per module); lead answers H-A-3, H-A-35, H-A-51, H-A-52, H-A-53, H-A-66, H-A-70, H-A-72, H-A-83 (1), H-A-85, H-A-88

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 10c806fe6f A4: a want names a version, never a part's digest or a keeping node
withKept names the released version alone; the want-parts reading
(Nodes.ReadsParts, WantParts, the node record's capabilities read for it) and
sayParts, which said why a want named no parts, go. The builder's parts and
keeping node stay read only to find a build's released version.

Builds: design 47 H §750, §764; H-A-37

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben c67bfcdc0f A3: the assigner keeps no order waits; the order on a machine is its node-engine's
The order waits go whole: orderwaits.go (order.<node>.<module>.<part> in the state
waits, their wait-held and wait-ended, the catalog entries read for a form change),
the package internal/acting, the want rule's acting edges (Module.Acting,
actingWaiting, ActingRuns, Nodes.Serves), the why record's acting reads, the release
how `now` and the order rows of assigner_waits, and the consumption of the indexer's
take-in.taken that fed the taken-in edge. assigner_waits and assigner_release keep
the outside waits and the puts.

Builds: design 47 H §771, §764; H-A-55

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben ff2211b3a1 A2: the assigner holds no want for an acting part's new version
The acting waits go whole: actingwaits.go (the waits acting.<node>.<module>.<part>,
their wait-held and wait-ended, the acting-cycle finding), the acting half of
internal/acting, the cycles among the acting waits and the node-engine read for them
(assigngraph's Cycles, HeldCycles, Engines) and the wait's bound on an acting edge;
the edge itself stays, kind acting, for the order it gives. assigner_waits and
assigner_release keep the order waits (A3) and the outside waits.

Builds: design 47 H §750, §764; H-A-70

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben e94a5d1256 R1: the test runs' whole test waits for its take-in's pipeline
It ended the build of main.3.app before the take-in had written it,
which passed only because the runner's resume swept the pipeline in
first; with no sweep the take-in alone starts it.

Builds: design 47 H §747

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben b53555c5bf A1: the assigner holds no want for a dependency's delivery
The version-delivered holds go whole: delivered.go (the delivery judgement,
the delivery waits, the asks to say a version delivered again), the states
delivery-waits and delivered-again, the tool assigner_delivered_again, the
consumption of mesh-wants.version-delivered and assigner_release's step
delivery. What it also heard and the want rule reads (version-released,
machine-away, machine-back) stays, in releases.go.

Builds: design 47 H §750, §764

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 3ad2ac455a R3: the runner says no pinned or freed; a pipeline's pins are the indexer's
The runner's pins of a pipeline's catalog revision (pins.go, PinRunning at its
start, the pin at a start, a rerun and an ask again, the free at an end) go;
the indexer pins on the take-in's write and on pipeline-started, and frees on
pipeline-ended (its half of §749, written by the indexer's developer).

Builds: design 47 H §749, §763, §764

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben def28437ce R2: the runner hears only the ends of the steps it asked itself
A build seat's step-ended naming another asker (the assigner's composer build,
which names no pipeline) was read against the runner's store, refused and
terminated; it is now taken as nothing, read before any pipeline, and
acknowledged.

Builds: design 47 G §24, §69

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben 5009109fad R1: the runner starts no pipeline by sweep, only on the events that name one
A take-in starts its own entries' pipelines alone; neither it nor the runner's
resume starts a module whose fingerprint has no pipeline (StartUnstarted,
Unstarted removed, their test turned into its inverse).

Builds: design 47 H §747, §764

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:31 +01:00
jschoubben dad31f49c5 H-A-48: the own build and the pull-request candidates' leftovers go
Nothing of the one model reads which build the indexer runs: the take-in holds nothing for the
indexer a revision names and indexer_pending answers the state held alone, so FixOwnBuild, the
state own-build, the ask of the node-engine's composition and its invoke go. No pull request's
candidate is written any more, so what only it read goes: the member heads' packages
(candidatePublished), SameCandidate, headOf and CandidatesKey; and consumerSink with the state
consumers (H-A-80). The state taken stays: the view reads it. The run on request's candidate
stays (H-A-105 b). The manifest test holds the state and the invoke absent.

Builds: design 47 H §743 (holds nothing for the indexer), §764 (the indexer); H-A-48, H-A-80, H-A-102, H-A-105

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:28 +01:00
jschoubben 1a3664ad77 I10: the indexer's integration tests drive the one model
The whole test starts the indexer against an embedded bus with the gate's source-moved on its
kept stream and a durable per watched branch: a first revision with start true and no movers;
one revision per take-in carrying its movers, pinned pipeline.<branch>.<source> and said as
take-in.taken; the same source-moved given again said from the kept movers with no second
revision; pipeline-started pinning, a restart keeping a running pipeline's revision; a take-in
on a full store held, said once as take-in.pending and in the state held, taken again on the
indexer's own room once pipeline-ended frees a pin; another branch's held take-in leaving
main going on, skipped by hand with why in the hand-act log; a branch watched later bound on
registration-changed. The packages test takes a mesh-sdk commit in and names mesh-sdk and the
module requiring it, not the one requiring nothing of it. The toolchain test drives take-ins;
the tests of the forge messages, the verdicts, the pins events of the gate and the view moving
between take-ins (H-A-49, H-A-103) go. 7 integration tests (was 13).

Builds: design 47 H §743, §744, §749, §768; H-A-12, H-A-30, H-A-49, H-A-50, H-A-90, H-A-92, H-A-97, H-A-102, H-A-103

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:28 +01:00
jschoubben c2e4d7914a H-A-48: the tests read no source stamp the seat's modules value no longer has
C1d takes src and fp-src from the seat mesh-catalog's modules value, so the checks of their
absence are held by the type and go.

Builds: design 47 H §764 (the indexer); H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:28 +01:00
jschoubben fd68792614 meshcatalogclient: an unreached entry is asked again, at most entry-asks times
An entry whose ask failed in transport is asked again when the followed branch says
catalog-revision and when the part's link opens again (AskAgain), at most Asks times (the
part's setting entry-asks, default 5); one more failure makes it unanswered, and
WriteEntryFindings writes the finding entry-unanswered, cleared by its answer or its release.

Builds: design 47 H (H-A-60, the entry asked again)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:28 +01:00
jschoubben 4611f263f3 H-A-48: the takeins ask keeps no field of the earlier take-in
The pending wait, the abandon, the merge by hand with its repository and sequence, and their
ask builders go; an ask naming only one of them is refused as naming no hand act.

Builds: design 47 H §744, §764 (the indexer); H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 1ece9449fd H-A-48, H-A-105: the builder-log index and indexer_take_in go
TakeIn, TakeInRepository, the catch-up, IndexRegistered and RetryUnread go: a module is taken in
only from a source revision, and the gate's gate_head_take is the one hand take of a head. The
manifest serves no indexer_take_in and names no catch-up tool beside the catalog revisions.

Builds: design 47 H §742, §764 (the indexer); H-A-48, H-A-105 (a)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 8d2d490637 H-A-48: no source stamp on a module; the take-in's commit names it
srcOf and the Src and FpSrc stamps go with the source per merged message: a module's value and
its catalog entry carry where it was taken in by its commit alone.

Builds: design 47 H §764 (the indexer); H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben e102f7dbc6 H-A-48: a pull request's seat definitions go; the trunk's alone are kept
keepPull, dropPull, ApplyVerdict and the pull form of the seat-definitions key go with the
pull and open messages and the checker's verdict; indexer_seat_definitions_again and
indexer_seat_definition name the trunk alone.

Builds: design 47 H §764 (the indexer); H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 204cf3e16a H-A-80: indexer_consumer goes with the state consumers
No ledger writes the state consumers any more, so the tool indexer_consumer, its reader and
the state's declaration go; the manifest test holds their absence.

Builds: design 47 H §764 (the indexer); H-A-80

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 3447dd5f4d I6: indexer_pin_drop drops a pin by its key; the held asks are read
I6: indexer_unpin is renamed indexer_pin_drop and takes the pin's key <branch>.<revision>
and why: it drops every record's pin of that key, clears its finding pin-missing and the
removal rule then applies; a hand act recorded in the hand-act log before it is asked
(§765, H-A-57).

I5 follow-up: the asks of indexer_take_in_pending and indexer_take_in_skip were refused by
the ask reader (DecodeTakeIn named no held branch); they are read now, and
indexer_pending answers {held: [{branch, source, why, since}]}, since in RFC 3339, the
state held's form (H-A-102). The test drives each tool's ask through the reader.

Builds: design 47 H §765 (indexer_pin_drop), §744 (the held tools); H-A-57, H-A-97, H-A-102

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 1b8f377cad I5: a take-in that cannot be written is held, said once and skippable
A source-moved the indexer cannot take in (the catalog store full, a read unanswered) stays
unacknowledged on its branch's consumer, so that branch's next waits while another branch's
go on; it is written in the new state held, one key per branch {branch, source, why, since}
(H-A-97), and said once per source as take-in.pending {branch, source, why}. A full store
sets heldFull, so RoomAgain says room once it has room, and the indexer's own room (H-A-50),
heard on its events consumer, takes every held one again, never a timer. indexer_pending
reads the state held; indexer_take_in_pending takes a branch's held one again now and
indexer_take_in_skip, with branch, source and why, acknowledges it unwritten, says
take-in.taken with no entries, skipped, by and why, and is recorded in the hand-act log;
both are asks in the state takeins. The held key goes at the take-in or the skip.

Builds: design 47 H §744; H-A-12, H-A-50, H-A-97

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 9ee012bce5 I1: one durable consumer per watched branch hears source-moved
The indexer binds one durable consumer per watched branch on the stream of the gate's
source-moved, named <node>_<indexer>_<escaped branch> through mesh-sdk's
Account.NamedEventConsumer; it takes each message in with TakeInSource and acknowledges it
once its revision and take-in.taken are written, and leaves it unacknowledged when the
take-in fails. The watched branches are the registrations'; a newly watched branch's
consumer is bound on the indexer's own registration-changed, which the manifest now
consumes. A source-moved of the old form (no call) is refused for good with a journal line.

Builds: design 47 H §743 (one durable per watched branch), §765 (the old form refused); H-A-30, H-A-90

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben d40e922be4 I4: predefined is read from the take-in of the catalog's commit
The take-in of a source revision moving the catalogue repository reads predefined.json from
that commit's trees through the seat git (wholeAt) and rewrites the state predefined when a
key changes. The read was already the take-in's (I8's wholeAt); this test holds it at the
take-in, and fails when the take-in writes no predefined.

Builds: design 47 H §769

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben b4f0c3ec88 I3: a branch's first source revision is taken in with no movers
A source-moved with start true, the seed of a branch's first revision, keeps its revision
with every module's entry at the heads it names and says take-in.taken with no entries and
no pin; a later take-in's movers are judged against those entries.

Builds: design 47 H §768 (the indexer's half), §743 (no mover); H-A-19

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben abdd70d918 I2b: one catalog revision per take-in, <branch>.<source>, carrying its movers
TakeInSource takes a gate's source-moved in: the trees of each repository it moves at the
named commit through the seat git, the fingerprints of the modules registered for it, the
movers against the branch's newest catalog revision, and one revision <escaped
branch>.<source> for every branch, the trunk included, numbered by the source and written
once by read before write. The revision carries its movers, and a redelivery whose revision
is kept says take-in.taken again from them, recomputing nothing (H-A-92). It is pinned for
the take-in's pipeline as pipeline.<branch>.<source> in the same write when it has a mover,
none for a take-in with no mover. take-in.taken carries branch, source, revision, call and
the movers' entries alone, under a duplicate id of its branch and source (H-A-31). A
source-moved with no call is refused as the old form (§765).

Only a take-in keeps a catalog revision (H-A-49): the recompute, the build ends' imports and
the start's reconcile keep none, and KeepView, keepEntries, keepTrunkRevision and
PinPipelines go. Another branch than the first is taken in on its newest revision's view.

Builds: design 47 H §743, §749 (the pin in the take-in's write), §765 (the old form); H-A-31, H-A-32, H-A-49, H-A-92

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben d00ee48363 I2a: the movers of a take-in are the moved fingerprints and their importers
A take-in's movers are the modules registered for a repository the source revision moved
whose fingerprint differs from their entry in the branch's newest catalog revision, and
every module, in any repository, importing a package one of them publishes. A module of
another repository is no mover by its fingerprint alone; one with no build is none.

Builds: design 47 H §743 (movers); A-476a

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 1e826ff008 I8, H-A-82: the earlier take-in goes; no delivered version is kept
I8: the take-in fed by the forge bridge's messages goes with B1's forgemsg: the FORGE
consumer and its handlers, the group end, the pending state with its keys, claims, dry
take-in and hand tools (indexer_pending, indexer_take_in_pending, indexer_drop_pending,
indexer_take_in_merge, kept again for the held take-in in I5), the catch-up by comparison
(kickBehind, TakeInBehind, sayUntaken, takeInHeads, kickCatchUp, CatchUp, merge-untaken),
the source numbering in memory (nextSource), the source verb's follow and Src stamping on
a source answer, the bridge's merged message call, the pull request candidates written
from pull and open messages, the checker's previews and verdict hearing. A repository's
trees at a commit are the internal whole (wholeAt), which ApplyMessage takes in; the dry
indexer stays for a run on request's candidate. The manifest drops the consumes of
forge.**, the checker's verdict and version-delivered, the reads of the checker's
previews and the invokes of open-pulls, bridge_merged_message and mesh-delivery.source.
RoomAgain says room when a take-in is held on a full store (heldFull, I5 holds it).

H-A-82: the fill of delivered versions into the edges goes: HearVersionDelivered, the
delivered.<module> key, the first fill's kinds 2, 4 and 6 from the placement and the
stream running, and outdated's kinds 2, 4 and 6; their entries read not yet delivered.

The tests of the removed paths go (index_test's candidate groups, source_test,
branch_take_in_test, previews_test, candidate_manifests_test, the FORGE handle tests);
the versions tests now hold kinds 2, 4 and 6 as declarations. The integration tests
still drive FORGE and are rewritten in I10.

Builds: design 47 H §743, §744, §764 (the indexer); H-A-48, H-A-82

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben ea28f39319 I7, I6 (the pins' events): no validation at the take-in; a pipeline's events pin its revision
I7: the indexer judges no manifest. The judge pass, its verdicts and unjudged states,
the events manifest-accepted and manifest-refused, the tools verdicts, indexer_verdicts,
indexer_judge and indexer_say_accepted, and the take-in's wait for the verdicts state
go; indexer_bus_state answers from the modules state at its mark. The seed writes
validate required in every policy. oldsections stays (H-A-79).

I6, the half that follows C-R: the gate's pinned, freed, heads-replaced and
pins-stated are no longer heard. A pipeline-started pins the revision it names under
pipeline.<branch>.<source>, its pipeline-ended frees it, each on a durable of its own
stream; kept revisions are judged against the pins the state holds, never a count
(made and pins-stated go). A take-in pins its revision once, for its one pipeline.
indexer_pin_drop (§765) is still to do.

The entry's pull goes (§763). The tests of the old take-in (pending, behind, pushed)
go with it, ahead of I8. The unit suite is green except manifest_test's check that
the watchman's and the grants part's invokes of the indexer's verdicts tools are
served: their removal is the contracts developer's (H-A-79).

Builds: design 47 H §743, §745, §749, §763, §764 (the indexer); H-A-48, H-A-49, H-A-79

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben 930d09cadc H-A-66: the indexer's revision verb, first views and seat-list part keep no callers
Every account may call every verb: the verb revision answers every caller, so its
callers list and the node-engine account's mapping go; the first-view tools take no
callers list and the tools bundle's env carries none; the seat-list part is made
without one.

Red only from the contract removals C1 and C3 (I7's manifest events, the gate's pin
events, the entry's pull), followed in the next commits.

Builds: design 47 H §752, §764 (every seat contract: callers); H-A-41, H-A-66

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben cbf1dbb15d I9: register, watch and the seed read no branch's protection
The forge's branch protection is no longer a condition of the mesh: register and watch
refuse only a reserved branch name, and the seed leaves out no module for its default
branch's protection and reads none.

The module compiles again only once C0 to C3's removals are all followed (H-A-66's
callers, I7's manifest events, the gate's pin events, the entry's pull); its unit
suite runs green from that commit on.

Builds: design 47 H §763 (G §5), §764 (the branch protection)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:56:27 +01:00
jschoubben f9e2dc38d8 W1: the watchman's whole test: a pipeline waiting behind another raises nothing
The indexer holds a source and takes it in, the runner writes its pipeline
waiting its turn (wait-held, step pipeline, on pipelines-at-once) ten minutes
back with no step asked, and the pipeline ahead of it stands: no take-in-waits,
no pipeline-stands and no head-untaken name the waiting one.

Builds: design 47 H §741, §748

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:51:07 +01:00
jschoubben 94d3f02f76 B-src: the builder's floor wakes on the indexer's take-in.taken
The seat mesh-catalog defines no manifest-accepted any more: the builder
consumes the indexer's take-in.taken in its place (module.json, names.go's
patterns) and wakes its floor on every one, looking at every module again as
before (versions.go, the wake take-in.taken). With the in-progress commit
before it the builder reads no source stamp and its untagged suite is green.

Builds: design 47 H §764 (the indexer: its events manifest-refused and manifest-accepted, with their reader); lead answers H-A-48, H-A-49, H-A-66, H-A-116 (hq 508faf0c)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:48:48 +01:00
jschoubben 11a22fdff7 X1: the checker goes: its module, its seat definition and its readers
The module mesh-delivery-checker goes whole with its manifest, and its seat's
definition leaves the seat list. The status view reads no tries: build_usage
answers no tries running and counts no step as a try. The grants part grants
main's accept subject to the builder alone. The tests name no checker as an
asker or a seat. The seat's generated packages, the indexer's readers and the
assigner's verdict constants go in the join's cleanup, once those branches
stand on this one (the lead, 2026-11-20).

Builds: design 47 H §764 (the checker (H1): mesh-delivery-checker whole); lead answer H-A-57 (hq f599b761)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:47:16 +01:00
jschoubben 90f53608bc B-src (in progress): the builder reads no source stamp
A module value carries no source stamp (C1d): ModuleOf takes none from the
entry's inputs, a build's claim is numbered per fingerprint naming no source
revision and no merge, and the log's started entry names none. The seat list's
parts take no callers and resolve no caller's holder (mesh-sdk's NewPart without
callers, SDK-C). internal/... is green; cmd/mesh-delivery-builder still hears
manifest-accepted (names.go:21, versions.go:192, module.json:57), which the
seat mesh-catalog no longer defines: its floor's wake is H-A-49's, asked of the
lead.

Builds: design 47 H §764 (the indexer: the field pull, the source numbering); lead answers H-A-48, H-A-66 (hq f599b761)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:43:10 +01:00
jschoubben 2bb08b9306 G1: the grants part's tests read no verdicts and no callers
The root package's tests and the part's whole test no longer write or read the
indexer's verdicts: a value whose verdict field says refused is composed as
ever (a module in a revision is accepted by being there), and a held module is
one whose manifest the part cannot read. The verdicts' first view row reads the
four first views; the no-verdict window and the want's newest build rows go; the
compare rows carry the denies every account now has, being granted every verb of
every seat; the seat list's again tool's caller row goes with the callers; the
captured nats manifest consumes catalog-revision, as the catalog's does, not the
retired manifest-accepted.

Builds: design 47 H §745, §752, §764 (every seat contract: the callers lists); lead answers H-A-66, H-A-79, H-A-113 (hq f599b761)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:39:46 +01:00
jschoubben ffb5c48dd2 SDK-C: a composer case carries no verdicts
The composer judges no manifest and the assigner's composition step sets
no verdicts, so Case.Verdicts goes with its words; a case carrying
verdicts was read before and is refused by a strict reader now.

Builds: design 47 H §745, §764 (the indexer: the validation at the take-in); lead answer H-A-112

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:28:59 +01:00
jschoubben 6b43adafca G1 (in progress): the grants part reads no callers and no verdicts
Every account may call every verb: the grants part reads no definition's
callers (callerOf, the verb and accept callers, admits) and grants every
module's account every verb of every seat (mesh.seat.*.tool.> and its
caller-named form), a sent store to every module invoking a verb of its
claimant's seat, and every queue's named ask to every asker. grants_callers
goes; grants_why_refused answers the bus's own verdict. The indexer keeps
no verdicts: their first view, events, invoke and the engine's read go, and
a want names its build alone (no newest). internal/... and cmd/... tests are
green; the root package's grants_test.go still reads the verdicts (rows at
grants_test.go:303-307, 741, 1184, 3700-3870, 4560-4615) and does not compile.

Builds: design 47 H §745, §750, §752, §764 (every seat contract: the callers lists); lead answers H-A-37, H-A-66, H-A-79, H-A-113 (hq f599b761)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:28:04 +01:00
jschoubben f8eea0000a V1: the view reads the H1 want, source, source-moved and held take-ins
A want counts as applied by its fingerprint and a motion event is keyed by
it; the want's newest and rule, and the state held back read from them, go
with the assigner's holds. A branch's source is {v, source, call, heads}
with no group, its source-moved is read by its source, and the delivered
event names no group. indexer_pending's held take-ins are said in the
tiers' pending words with their branch, source, why and since, naming no
module. The view reads no source stamp on a module. Its seat list, its
first-view tool answers and its manifest name no callers; its source invoke
reads call, not group.

Builds: design 47 H §737, §744, §750, §752, §764 (the gate's groups; the indexer's pending and groups; the assigner's holds; the callers lists); lead answers H-A-26, H-A-37, H-A-48, H-A-66, H-A-78, H-A-102, H-A-109 (hq 3433db0e)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:20:33 +01:00
jschoubben 9a55e6e8c0 C1d: the seat mesh-catalog's module and inputs carry no source stamps
The indexer stamps no source revision on a module (the take-in's commit
names it), so the seat mesh-catalog's state modules value and EntryInputs
lose src and fp-src, and the fixture rows their stamps. A module value or an
entry's inputs carrying either was read before and is refused now.

Builds: design 47 H §764 (the indexer); lead answer H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:15:20 +01:00
jschoubben 78e169a8c6 C-R5: the runner's pipeline keeps the movers superseded out of it
The seat mesh-pipeline-runner's Pipeline gains superseded, the modules a
newer waiting take-in of the same branch took out of the pipeline, written
with the movers by compare-and-set, so the runner writes a mover's
build-step why from it at the pipeline's placing. A fixture row of a waiting
pipeline naming one failed to read back before the field was defined.

Builds: design 47 H §748; lead answer H-A-107 (hq fabb927f)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:11:18 +01:00
jschoubben f6163349af W1: the watchman reads the H1 take-in, the mover's entry and the want
The watchman follows the one model in one pass. Its take-in waits are the seat's take-in.pending
and take-in.taken, keyed <branch>.<source>, timed from the message's own time by the setting
take-in-bound (60 minutes by default), and seeded from indexer_pending's held take-ins; the group
bound goes. A taken-in mover's bus state is read from its catalog entry by fingerprint through
the seat mesh-catalog's verb entry, bus-state-overdue timed from the take-in. The manifest
verdicts and their findings, the head timing of source-moved, acting-part-late and
delivery-waits go, with their readers, consumes and the indexer_verdicts invoke. A want awaiting
its hand placement is not timed, and the want readers follow the H1 want. A record-opened is
heard on record-opened.<call>.

Builds: design 47 H §741, §744, §764 (the indexer: manifest-refused, manifest-accepted, the
watchman's findings; the assigner: acting-part-late, delivery-waits), §772; lead answers H-A-25,
H-A-37, H-A-49, H-A-70, H-A-78 (2), H-A-79, H-A-91 (2), H-A-94, H-A-95 (1), H-A-97, H-A-102

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:05:11 +01:00
jschoubben 5bf6fd9b01 graph: the refused cycle is shared code, read by the indexer and the validate step
RefusedCycle, with its running-version break and its path search, moves from the indexer's
internal/index into mesh-delivery-sdk/graph, so the assigner's validate step reads the same rule
the indexer's take-in does; the indexer calls the shared function. The rule's table test moves
with it; the indexer keeps its test of the trunk catalogues against the shared rule.

Builds: design 47 H §745; lead answers H-A-34, H-A-104 (2)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:00:13 +01:00
jschoubben 89e0926feb C-R4: the runner's rerun, accept and ask-again name the mover's module
A pipeline of several movers is never ambiguous: the seat mesh-pipeline-runner's verbs rerun,
accept and ask-again gain the optional input module, the mover's; a call naming none on a
pipeline of one mover is taken as that mover. Fixture rows of each verb's input name a module
and failed to read back before the field was defined.

Builds: design 47 H §746; lead answer H-A-101 (1)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:52:48 +01:00
jschoubben c94e8564e6 C-R3: the runner's queue keeps the pipelines running
The seat mesh-pipeline-runner's state queue gains the key form running.<pipeline>, value
{pipeline}, written when a pipeline is placed and deleted at its end, its cancel or its approval
wait, so pipelines-at-once is judged against the running keys alone. A fixture row reads the new
form; the generator refused it before the form was defined.

Builds: design 47 H §748; lead answer H-A-96

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:49:06 +01:00
jschoubben 969caea37f C3c: the seat mesh-delivery's owed acts keep no merge's ask or group
The Owed definition's fields ask and group were kept only for a merge, and the owed act merge
went in C3b; nothing reads them, so they leave the definition and the generated contracts. A row
of the client's test reads the definition and fails while either field is in it.

Builds: design 47 H §764 (the forge bridge: the merge act of a switched key); lead answer H-A-95 (2)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:48:23 +01:00
jschoubben be741a7a8f C1c: a catalog revision carries its movers
The seat mesh-catalog's CatalogRevision gains movers, the take-in's entries
({module, commit, fingerprint, repository}), so a redelivered source-moved whose revision is
already kept says take-in.taken again from them, recomputing nothing. The branch revision's
fixture names one mover; the generated fixture test fails without the field.

Builds: design 47 H §743; lead answer H-A-92 (hq 8c0b04e3)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:40:18 +01:00
jschoubben f79c0a7b78 C3b: the seat mesh-delivery's owed acts name no merge
The bridge performs no merge since the merge call (design 47 H §764), so the owed act merge
(OwedActMerge) leaves the seat's definition, its fixture and the generated contracts; the
bridge's tests no longer read a merge fixture to refuse. A row of the client's test reads the
definition's act enum and fails while merge is in it.

Builds: design 47 H §764 (the forge bridge: the merge act of a switched key); lead answer H-A-91 (3)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:39:29 +01:00
jschoubben 9fe6330d79 B4: the bridge's whole test says head-moved; bridge_heads reads the heads held
The bridge's whole test runs the program against an embedded bus as the node does: a start, a
merge, an admitted push to an unprotected branch and a restart after a move each give one
head-moved naming the head read through the seat git's branch and the head held before (start
true at a start); a head heard twice, a branch not watched and a restart at the head held give
none, and the bridge asks the seat git nothing but branch. Its bus permissions are composed for
the manifest as it now stands. The pull, open pull request, group and unprotected-branch tests
go; the owed test performs the gate's statuses once, after a restart and again by hand.

bridge_heads answers each key of the state heads with the head the bridge holds, read-only.

Builds: design 47 H §739 (how checked), §774; lead answers H-A-48, H-A-85 (1)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:34:07 +01:00
jschoubben 7ac48fd882 B2, B3: the forge bridge says head-moved and carries the one model
B2: on every branch-moved of a watched branch, and at its start for every watched branch's head,
the bridge reads the head through the seat git's verb branch, as a kept call that waits on the
holder's return while the branch is watched, and writes one head-moved (repository, branch,
head, before the head held in its state heads, start) on its stream forge; a head equal to the
one held writes nothing. It reads no pull request, no tree, no file and no protection: the
merged and pushed messages, their inputs and the state inputs, the call of git.pull, the finding
branch-unprotected with its held finding writer, and the ten-second redelivery go. A move whose
head cannot be read is left unacknowledged for the bus to deliver again.

B3: the pull-message path (Convert, the open pull requests at start and reconnect, the
forge-delete message), the groups (internal/groups' group part, forge.group.merged, end-asks,
bridge_groups, bridge_group_end_again), bridge_merged_message with the forge-made reader, the
checker's owed and the merge act of a switched key (with the switch's bookkeeping read) go, with
their consumes, invokes, states and requires. The gate's owed path stays (H-A-71), its catch-up
from the gate's verb groups gone with that verb.

The two meet in main.go and the package compiles only with both, as it did not since B1. The
unit suites pass; the whole test (integration) is rewritten in B4.

Builds: design 47 H §739, §764 (the forge bridge; the branch protection); lead answers H-A-23, H-A-27, H-A-48, H-A-71

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:31:04 +01:00
jschoubben 3560362330 C-W2: a step the assigner serves names its asker
The seat mesh-wants' StepRun gains asker, the seat name of the part asking the step (the runner
writes mesh-pipeline-runner), so the assigner names a step's progress with it. Optional in the
definition: the line names its writer, not that a step without it is refused. Both accept:step
fixtures carry it; the generated fixture test fails without the field.

Builds: design 47 H §745; lead answer H-A-88 (hq 2c6c7c03), H-A-41

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:27:41 +01:00
jschoubben 87e9084e15 C-R2: the runner's pipelines key a run on request; a mover keeps its heard publishes
The seat mesh-pipeline-runner's state pipelines gains the key form <branch>.run.<run>, one
pipeline per run on request, its movers the named commits' modules (it delivers nothing). Its
Mover gains published, the artifact references whose package-published (or, on a kind-3 edge,
whose build step's passed end) the runner heard at the pipeline's branch and source, kept with
the pipeline so a dependency's wait survives a restart. A fixture of the new key form with a
mover naming one heard publish proves both.

Builds: design 47 H §746; lead answers H-A-83 (1) (hq ae7fc40a), H-A-84 (hq main 0631f43f+)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:21:43 +01:00
jschoubben b75dcc947c C1b: the seat mesh-catalog keeps no state verdicts
With the validation gone from the take-in, the state verdicts, its value and the client's
helpers over it (VerdictsKey, TakeVerdict, VerdictWhy, ModuleVerdict, the codec) leave the
seat's contract; a module's own verdict field keeps its three states.

Builds: design 47 H §745, §764 (the indexer: the validation at the take-in); lead answer H-A-79

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:15:15 +01:00
jschoubben 630c099972 B1: the forge bridge's one message, head-moved
forgemsg holds one message per move of a watched branch's head: head-moved with repository,
branch, head, before and start, on forge.<owner>.<name>.<escaped branch>.head-moved, refusing
a head equal to the one held and any field it does not have (trees, base). The messages pull,
merged, pushed, refused and open, their trees, inputs, group and members, and the group's end
forge.group.merged go; owed.ended stays.

Builds: design 47 H §739, §764 (the forge bridge: merged, pushed, base, the group's end); lead answers H-A-27, H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:13:15 +01:00
jschoubben f9fa0ec2b2 C-W: a want awaiting its hand placement is held
The assigner holds the want of a node whose node-engine does not state want:version in the
want's hold field, its words awaits-hand-placement; the client takes that hold beside a put's
and refuses a hold with other words.

Builds: design 47 H §772; lead answer H-A-73

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:09:23 +01:00
jschoubben 83d454217f steprun: the asker judgement goes; every asker's kind is taken
The step runner no longer reads the seat list for the callers a build seat's definition
lists, refuses an asker it does not name, or gives an ask back until the list says:
Puller.Callers, CallersFromDefinitions, SeatListCallers and the seat list reader's start
go, since no seat definition names callers and every account may call every verb. The
step is still keyed under the asker its subject names, and main's subject still takes
only a build, a run and the checker's check and recheck. mesh-delivery-sdk builds again
against mesh-sdk without seatdef callers.

Builds: design 47 H §752, §764 (every seat contract: the callers lists); lead answers H-A-41, H-A-66, H-A-71 (3)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:09:01 +01:00
jschoubben 4599d2e60f C-W: the seat mesh-wants: a want by version, pipeline and rank; pipeline-wanted; validate
A module want names its fingerprint and released version with the pipeline (<branch>.<source>)
and rank (its tier, from 1) it was written from, neither for a placement's build; parts, rule,
newest, kept-on and composed go, and the client checks a rank with its pipeline instead of a
composition and a rule. The node's own want is unchanged. The accepted step and its end take
validate beside composition. wanted gains pipeline; pipeline-wanted.<branch>.<source> says a
pipeline's wants once at their end, running or tier-late with the movers and machines not
running. version-delivered goes.

Builds: design 47 H §745, §750, §751, §764 (the assigner: version-delivered, the digests in a want); lead answers H-A-37, H-A-51, H-A-56, H-A-72 (6), H-A-75

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:05:15 +01:00
jschoubben b7b4087095 C-R: the runner's seat: one pipeline per take-in, its movers, the queue and place
The pipeline is keyed <branch>.<source> (and <branch>.<source>.published.<package>.<version>
for a publish), its movers {module, commit, fingerprint, repository, tier} carry what was
per module (version, widens, tests, over-budget); group goes, run, published, unlogged and
end-count stay; call and seq are added and the outcome gains waiting. Each step result
names its module and the step enum gains validate. pipeline-started names the movers;
pipeline-ended carries per mover its fingerprint, version, steps and tier. pipeline-started,
pipeline-ended, wait-held and wait-ended are said on <branch>.<source>; the step events and
run-started on <module>.<branch>.<commit>. A wait gains step pipeline and on
pipelines-at-once. The state queue holds queue.next and waiting.<sequence>; the verb place
takes pipeline and why. group-ended and its body go. The client builds and parses both
subject forms.

Builds: design 47 H §745, §746, §747, §748, §764 (the runner: group-ended, the key per module); lead answers H-A-35, H-A-36, H-A-51, H-A-52, H-A-53, H-A-72 (1) to (5)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:01:24 +01:00
jschoubben d24d6a0890 C2: a kept call's member names its base branch
So the forge module can say merge-called for what landed after a restart
without reading the forge again, each member of the state calls keeps the
pull request's base, read at judging.

Builds: design 47 H §766; lead answer H-A-71 (2)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:51:26 +01:00
jschoubben 5042d9c426 C-acts: the build seats' acting rules name no bound
acts stays as the declaration the graph's edges and tiers are built from; the
bound of the build seats' rule goes with the acting part's hold. The generated
contracts do not change.

Builds: design 47 H §750, §764 (the acting part's hold); lead answers H-A-57, H-A-70

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:51:01 +01:00
jschoubben 6e027de597 C3: the source revision's contract: source-moved per source, record-opened per call, heads
source-moved is said on source-moved.<branch>.<source> with v, branch, source,
call, start and heads [{repository, commit}], kept 30 days and 64 MiB on its
own stream; its wildcard has two tokens (H-A-26). record-opened is said on
record-opened.<call>; it and record-ended carry branch, source and call, the
milestone <branch>.<source>, no forge-made fields (H-A-25). The source value
carries source and call, the verb source answers call; the state heads keeps
each untaken head {head, since} by <repository>.<branch>. The states merges,
asks and turns, the verb groups, and the events approval-carried, pinned,
freed, pins-stated and heads-replaced go (H-A-28, H-A-48), with their helpers
in meshdeliveryclient.

Builds: design 47 H §737, §740, §749, §764 (the gate's states, groups and switch); lead answers H-A-23, H-A-25, H-A-26, H-A-28, H-A-33, H-A-48

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:49:32 +01:00
jschoubben f8bbde9627 C2: the merge call's contract: merge-pull takes pulls and by, merge-called, calls
merge-pull takes a list of one or more members {repository, number, head} and
by, judges no branch protection and answers once, at the call's end, the call
and each member's outcome {repository, number, state, commit|why} (H-A-21,
H-A-22); its caller id goes, and it names a timeout of 120 s (H-A-43). The
seat says merge-called on merge-called.<call>, kept 30 days and 64 MiB on
SEAT_git_merge-called, its body in bodies; the state calls keeps each call
with said (H-A-47). branch answers no protected.

Builds: design 47 H §734, §735, §736, §766, §767, §764 (the single-pull form, the protection judgement); lead answers H-A-21, H-A-22, H-A-23, H-A-24, H-A-43, H-A-47

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:44:23 +01:00
jschoubben f006ab50bc C1: the take-in's form is the lines' fields; policies gain validate
take-in.taken carries branch, source, revision, call, entries (one
{module, commit, fingerprint, repository} per mover, no pull), skipped, and by
and why for a hand act; take-in.pending carries branch, source and why; the
keys, kinds, merges, groups and the other fields of the earlier take-in go, so
readers pair a wait by <branch>.<source> (H-A-31). StepStatuses gains
validate before composition; the seat says no manifest-accepted or
manifest-refused.

Builds: design 47 H §743, §744, §745, §763 (G §476, §648), §764 (the indexer's manifest events); lead answer H-A-31

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:41:07 +01:00
jschoubben 8e5e5dbb42 seatgen: an identifier splits on ':' too, so want:version is a Go constant
The node-engine seat's enum value want:version must yield a parseable Go
constant; ':' splits as '-', '_', '.' and a space do. No existing generated
output changes (the generator's check of mesh-delivery-contracts is unchanged).

Builds: design 47 H lead answer H-A-64

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:36:37 +01:00
jschoubben ce6edcd9b9 C0: no seat definition names callers; the generator refuses one that does
Every account may call every verb (ADR 0682 §10), so the callers lists of every
seat definition and part of mesh-delivery-contracts go, and the generator, the
one reader of definitions in this repository, refuses a verb or accepted kind
that names callers instead of checking its forms. The generated contracts do
not change: the generator made nothing of callers.

Builds: design 47 H §752, §764 (every seat contract: the callers lists)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 02:36:30 +01:00
633 changed files with 17755 additions and 63943 deletions
@@ -1,341 +0,0 @@
// Package meshdeliverycheckerclient holds the logic the holders and callers of the seat mesh-delivery-checker share over its
// contract (novox/hq ADR 0625 §4, ADR 0634 §2): the rules a verdict and a kept verdict must keep to be written or read. The
// checker writes them, and the view, the gate and the indexer read them; the contract's decoding is strict by schema only, so
// these rules are written once here and no caller copies them.
package meshdeliverycheckerclient
import (
"fmt"
pathpkg "path"
"strings"
checker "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// The states of a verdict, the levels of a check and the compositions' states.
const (
VerdictRunning = "running"
VerdictPass = "pass"
VerdictFail = "fail"
LevelUnit = "unit"
LevelIntegration = "integration"
CompositionNotRun = "not-run"
CompositionPass = "pass"
CompositionFail = "fail"
)
// MaxFailures is the most failures a verdict names; it names the count of the rest beside them.
const MaxFailures = 50
func checkLevel(level string) error {
if level != LevelUnit && level != LevelIntegration {
return fmt.Errorf("meshdeliverycheckerclient: the level %q is not %s or %s", level, LevelUnit, LevelIntegration)
}
return nil
}
func isHex12(s string) bool { return len(s) == 12 && strings.Trim(s, "0123456789abcdef") == "" }
// CheckRepository refuses a repository that is not <owner>/<name> with exactly one slash, each part a key part.
func CheckRepository(repository string) error {
owner, name, ok := strings.Cut(repository, "/")
if !ok || strings.Contains(name, "/") {
return fmt.Errorf("meshdeliverycheckerclient: the repository %q is not <owner>/<name>, with exactly one slash", repository)
}
if err := keys.CheckName("repository owner", owner); err != nil {
return fmt.Errorf("meshdeliverycheckerclient: the repository %q: %w", repository, err)
}
if err := keys.CheckName("repository name", name); err != nil {
return fmt.Errorf("meshdeliverycheckerclient: the repository %q: %w", repository, err)
}
return nil
}
func checkComposition(c *checker.VerdictsByGroupHeadsValueComposition) error {
if c == nil {
return nil
}
switch c.State {
case CompositionNotRun:
if c.Sdk != "" || len(c.Machines) > 0 {
return fmt.Errorf("meshdeliverycheckerclient: the verdict's composition is not run and names no mesh-sdk commit or machines")
}
case CompositionPass:
if c.Sdk == "" {
return fmt.Errorf("meshdeliverycheckerclient: the verdict's composition passed and names no mesh-sdk commit")
}
case CompositionFail:
if c.Words == "" {
return fmt.Errorf("meshdeliverycheckerclient: the verdict's composition failed and gives no words")
}
default:
return fmt.Errorf("meshdeliverycheckerclient: the verdict's composition state %q is not %s, %s or %s", c.State, CompositionNotRun, CompositionPass, CompositionFail)
}
return nil
}
// checkJudgedBy refuses a checking program named at no repository, full commit and package, kept under no program key,
// or over no head or a head at no full commit (novox/hq ADR 0644, ADR 0656; issue 1921).
func checkJudgedBy(j *checker.VerdictsByGroupHeadsValueJudgedBy) error {
const who = "meshdeliverycheckerclient: "
if j == nil {
return nil
}
if CheckRepository(j.Program.Repository) != nil || !isCommit(j.Program.Commit) || j.Program.Package == "" {
return fmt.Errorf(who+"the verdict is judged by a checking program built at no repository, full commit and package (%+v)", j.Program)
}
if !strings.HasPrefix(j.Key, "program-") {
return fmt.Errorf(who+"the verdict's checking program is kept under %q, which is no program key", j.Key)
}
if len(j.Heads) == 0 {
return fmt.Errorf(who + "the verdict's checking program read no head")
}
for _, h := range j.Heads {
if CheckRepository(h.Repository) != nil || !isCommit(h.Commit) {
return fmt.Errorf(who+"the verdict's checking program read %s at %q, which is no full commit", h.Repository, h.Commit)
}
}
return nil
}
func isCommit(s string) bool { return len(s) == 40 && strings.Trim(s, "0123456789abcdef") == "" }
// CheckVerdict refuses a verdict a reader could not place: no group, heads that are not 12 lowercase hex digits, a repository
// both merged and read beside, a carried-from that carries nothing, a series change from a series to itself or named twice, a
// level that is neither unit nor integration or counts a negative number, a time below zero, a pass that says nothing of a
// level, a fail that names neither a test nor a machine, and failures on a verdict that did not fail.
func CheckVerdict(v checker.VerdictsByGroupHeadsValue) error {
const who = "meshdeliverycheckerclient: "
if v.Group == "" {
return fmt.Errorf(who + "a verdict names no group")
}
if !isHex12(v.Heads) {
return fmt.Errorf(who+"the verdict's heads hash %q is not 12 lowercase hex digits", v.Heads)
}
for repository, head := range v.Trunk {
if head == "" {
return fmt.Errorf(who+"the verdict's trunk head of %s is empty", repository)
}
}
for repository, commit := range v.Beside {
if commit == "" {
return fmt.Errorf(who+"the verdict's sibling commit of %s is empty", repository)
}
if _, ok := v.Trunk[repository]; ok {
return fmt.Errorf(who+"the verdict names %s as a trunk it merged and as a sibling it read", repository)
}
}
if len(v.CarriedFrom) > 0 {
if v.State == VerdictRunning {
return fmt.Errorf(who + "a running verdict is carried from nothing: carried-from is written with its end")
}
moved := false
for repository, commit := range v.CarriedFrom {
now, inTrunk := v.Trunk[repository]
if !inTrunk {
now = v.Beside[repository]
}
if commit == "" || now == "" {
return fmt.Errorf(who+"the verdict's carried-from names %s, which it judged on no commit of", repository)
}
moved = moved || commit != now
}
if !moved {
return fmt.Errorf(who + "the verdict's carried-from names the commits it is judged on: nothing moved, so nothing was carried")
}
}
changed := map[string]bool{}
for _, c := range v.Series {
if c.Module == "" || c.Artifact == "" || c.From == "" || c.To == "" {
return fmt.Errorf(who+"the verdict's series change %+v names no module, artifact, from or to", c)
}
if c.From == c.To {
return fmt.Errorf(who+"the verdict's series change of %s/%s is from %s to the same series", c.Module, c.Artifact, c.From)
}
if changed[c.Module+"/"+c.Artifact] {
return fmt.Errorf(who+"the verdict names the series change of %s/%s twice", c.Module, c.Artifact)
}
changed[c.Module+"/"+c.Artifact] = true
}
for level, r := range v.Levels {
if err := checkLevel(level); err != nil {
return err
}
if r.Run < 0 || r.Kept < 0 || r.Skipped < 0 {
return fmt.Errorf(who+"the verdict's %s level counts a negative number of tests", level)
}
}
if err := checkComposition(v.Composition); err != nil {
return err
}
if err := checkJudgedBy(v.JudgedBy); err != nil {
return err
}
seen := map[string]bool{}
for _, level := range v.OverBound {
if err := checkLevel(level); err != nil {
return fmt.Errorf(who+"the verdict's over-bound names: %w", err)
}
if seen[level] {
return fmt.Errorf(who+"the verdict's over-bound names the level %s twice", level)
}
seen[level] = true
}
if t := v.Took; t != nil {
for part, ms := range map[string]int64{"queue": t.Queue, "clone": t.Clone, "unit": t.Unit, "lint": t.Lint,
"integration-setup": t.IntegrationSetup, "integration-run": t.IntegrationRun, "composition": t.Composition} {
if ms < 0 {
return fmt.Errorf(who+"the verdict's time of the part %s is negative", part)
}
}
}
named := v.Failed != nil && (v.Failed.Test != "" || v.Failed.Machine != "")
if len(v.Failures) > 0 && v.State != VerdictFail {
return fmt.Errorf(who+"a %s verdict names no failures", v.State)
}
if len(v.Failures) > MaxFailures+1 {
return fmt.Errorf(who+"the verdict names %d failures, more than %d and the count of the rest", len(v.Failures), MaxFailures)
}
switch v.State {
case VerdictRunning:
if v.Failed != nil && *v.Failed != (checker.VerdictsByGroupHeadsValueFailed{}) {
return fmt.Errorf(who + "a running verdict names no failure")
}
case VerdictPass:
if v.Failed != nil && *v.Failed != (checker.VerdictsByGroupHeadsValueFailed{}) {
return fmt.Errorf(who + "a pass names no failure")
}
for _, level := range []string{LevelUnit, LevelIntegration} {
if _, ok := v.Levels[level]; !ok {
return fmt.Errorf(who+"a pass says nothing of the %s level", level)
}
}
case VerdictFail:
if !named {
return fmt.Errorf(who + "a fail names neither a test nor a machine")
}
default:
return fmt.Errorf(who+"the verdict state %q is not running, pass or fail", v.State)
}
return nil
}
// CheckKept refuses a kept verdict that is not a pass of a repository's package at a level, with its toolchain and its time:
// a failure is never kept.
func CheckKept(k checker.KeptByLevelDigestValue) error {
const who = "meshdeliverycheckerclient: "
if k.State != VerdictPass {
return fmt.Errorf(who+"a kept verdict is a pass, never %q: a failure is never kept", k.State)
}
if err := CheckRepository(k.Repository); err != nil {
return err
}
if k.Package == "" {
return fmt.Errorf(who + "a kept verdict names no package")
}
if err := checkLevel(k.Level); err != nil {
return err
}
if k.Tests < 0 || k.Took < 0 {
return fmt.Errorf(who + "a kept verdict counts a negative number of tests or a negative time")
}
if k.Toolchain == "" {
return fmt.Errorf(who + "a kept verdict names no toolchain version")
}
if k.At == "" {
return fmt.Errorf(who + "a kept verdict says no time")
}
return nil
}
// CheckPreview refuses a preview a reader could not place (the checker writes it, the indexer reads it for the candidates'
// fingerprints): a repository, head or trunk commit that does not key, a head in conflict that names no file or has a merge
// commit or modules, a head that merged and names no merge commit, and a module with no directory, no tree, a manifest
// digest that is not 64 lowercase hex digits, a lock without path or hash, or a named path that is not clean and inside the
// module's directory or names no git object.
func CheckPreview(p checker.PreviewsByRepositoryHeadTrunkValue) error {
const who = "meshdeliverycheckerclient: "
if err := CheckRepository(p.Repository); err != nil {
return err
}
if err := keys.CheckName("head", p.Head); err != nil {
return fmt.Errorf(who+"the preview: %w", err)
}
if err := keys.CheckName("trunk commit", p.Trunk); err != nil {
return fmt.Errorf(who+"the preview: %w", err)
}
for _, f := range p.Conflicts {
if f == "" {
return fmt.Errorf(who + "a preview names a conflicting file with an empty path")
}
}
if len(p.Conflicts) > 0 {
if p.Merge != "" || len(p.Modules) > 0 {
return fmt.Errorf(who + "a preview of a head in conflict has no merge commit and no modules")
}
return nil
}
if p.Merge == "" {
return fmt.Errorf(who + "a preview names no merge commit")
}
for dir, m := range p.Modules {
if dir == "" {
return fmt.Errorf(who + "a preview names a module with an empty directory")
}
if m.Tree == "" {
return fmt.Errorf(who+"the preview's module %q has no tree", dir)
}
if !keys.IsHex64(m.Manifest) {
return fmt.Errorf(who+"the preview's module %q: %q is not a manifest digest, 64 lowercase hex digits", dir, m.Manifest)
}
for path, hash := range m.Locks {
if path == "" || hash == "" {
return fmt.Errorf(who+"the lock %q of the preview's module %q has an empty path or hash", path, dir)
}
}
for p, object := range m.Paths {
if p == "" || p != pathpkg.Clean(p) || strings.HasPrefix(p, "/") || p == ".." || strings.HasPrefix(p, "../") {
return fmt.Errorf(who+"the preview's module %q: the named path %q is not a clean path inside the module's directory", dir, p)
}
if object == "" {
return fmt.Errorf(who+"the preview's module %q: the named path %q names no git object", dir, p)
}
}
}
return nil
}
// VerdictKey is the key, in the state verdicts, of a group's check at its heads: `<escaped group>.<heads hash>`, the
// group escaped so a branch such as `fix/1.2` keys, the heads hash as the mesh-delivery client's HeadsHash gives it
// (12 lowercase hex digits).
func VerdictKey(group, headsHash string) (string, error) {
if group == "" {
return "", fmt.Errorf("meshdeliverycheckerclient: the group name is empty")
}
if !isHex12(headsHash) {
return "", fmt.Errorf("meshdeliverycheckerclient: %q is not a heads hash, 12 lowercase hex digits", headsHash)
}
return keys.EscapeName(group) + "." + headsHash, nil
}
// ParseVerdictKey is the inverse of VerdictKey.
func ParseVerdictKey(key string) (group, headsHash string, err error) {
i := strings.LastIndex(key, ".")
if i < 0 {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a verdict key, <group>.<heads hash>", key)
}
part, headsHash := key[:i], key[i+1:]
if !isHex12(headsHash) {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a verdict key: %q is not a heads hash, 12 lowercase hex digits", key, headsHash)
}
if part == "" || strings.Contains(part, ".") {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a verdict key: the group part is empty or holds a dot", key)
}
if group, err = keys.UnescapeName(part); err != nil {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a verdict key: %w", key, err)
}
return group, headsHash, nil
}
@@ -1,269 +0,0 @@
package meshdeliverycheckerclient
import (
"encoding/json"
"strings"
"testing"
checker "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker"
)
type verdict = checker.VerdictsByGroupHeadsValue
func passing() verdict {
return verdict{Group: "g", Heads: "0123456789ab", State: VerdictPass, Trunk: map[string]string{"novox/a": "c1"},
Levels: map[string]checker.VerdictsByGroupHeadsValueLevelsValue{LevelUnit: {Run: 3}, LevelIntegration: {Run: 1}}}
}
// The rules a verdict keeps to be written or read: each case edits a passing verdict and names what the refusal says.
func TestAVerdictIsRefusedForWhatAReaderCouldNotPlace(t *testing.T) {
if err := CheckVerdict(passing()); err != nil {
t.Fatalf("a passing verdict is refused: %v", err)
}
for name, c := range map[string]struct {
edit func(*verdict)
says string
}{
"no group": {func(v *verdict) { v.Group = "" }, "no group"},
"heads of 11 digits": {func(v *verdict) { v.Heads = "0123456789a" }, "12 lowercase hex"},
"an empty trunk head": {func(v *verdict) { v.Trunk["novox/a"] = "" }, "trunk head"},
"merged and read": {func(v *verdict) { v.Beside = map[string]string{"novox/a": "c2"} }, "trunk it merged and as a sibling"},
"nothing carried": {func(v *verdict) { v.CarriedFrom = map[string]string{"novox/a": "c1"} }, "nothing moved"},
"a running carry": {func(v *verdict) { v.State, v.CarriedFrom = VerdictRunning, map[string]string{"novox/a": "c0"} }, "carried from nothing"},
"a series to itself": {func(v *verdict) {
v.Series = []checker.VerdictsByGroupHeadsValueSeriesItem{{Module: "m", Artifact: "a", From: "0.1", To: "0.1"}}
}, "same series"},
"an unknown level": {func(v *verdict) { v.Levels["smoke"] = checker.VerdictsByGroupHeadsValueLevelsValue{} }, "smoke"},
"a negative count": {func(v *verdict) { v.Levels[LevelUnit] = checker.VerdictsByGroupHeadsValueLevelsValue{Run: -1} }, "negative"},
"a negative time": {func(v *verdict) { v.Took = &checker.VerdictsByGroupHeadsValueTook{Unit: -1} }, "negative"},
"a pass without a level": {func(v *verdict) { delete(v.Levels, LevelIntegration) }, "integration level"},
"a pass that failed": {func(v *verdict) { v.Failed = &checker.VerdictsByGroupHeadsValueFailed{Test: "T"} }, "names no failure"},
"failures of a pass": {func(v *verdict) { v.Failures = []checker.VerdictsByGroupHeadsValueFailuresItem{{Test: "T"}} }, "names no failures"},
"a fail naming nothing": {func(v *verdict) { v.State = VerdictFail }, "neither a test nor a machine"},
"an unknown state": {func(v *verdict) { v.State = "maybe" }, "maybe"},
"a composition passed without a commit": {func(v *verdict) {
v.Composition = &checker.VerdictsByGroupHeadsValueComposition{State: CompositionPass}
}, "mesh-sdk commit"},
"the same level over bound twice": {func(v *verdict) { v.OverBound = []string{LevelUnit, LevelUnit} }, "twice"},
// 1921 (B0, G): the checking program that judged it.
"judged at no full commit": {func(v *verdict) { j := judgedBy(); j.Program.Commit = "0123456"; v.JudgedBy = &j }, "checking program built at no repository, full commit"},
"judged under no key": {func(v *verdict) { j := judgedBy(); j.Key = "composer-1"; v.JudgedBy = &j }, "composer-1"},
"judged over no head": {func(v *verdict) { j := judgedBy(); j.Heads = nil; v.JudgedBy = &j }, "no head"},
"judged over a branch": {func(v *verdict) { j := judgedBy(); j.Heads[0].Commit = "main"; v.JudgedBy = &j }, "novox/mesh-delivery"},
} {
v := passing()
c.edit(&v)
if err := CheckVerdict(v); err == nil || !strings.Contains(err.Error(), c.says) {
t.Errorf("%s: %v, want a refusal saying %q", name, err, c.says)
}
}
judged := passing()
j := judgedBy()
judged.JudgedBy = &j
if err := CheckVerdict(judged); err != nil {
t.Errorf("a pass judged by a checking program is refused: %v", err)
}
failed := passing()
failed.State, failed.Failed = VerdictFail, &checker.VerdictsByGroupHeadsValueFailed{Machine: "ace"}
if err := CheckVerdict(failed); err != nil {
t.Errorf("a fail naming a machine is refused: %v", err)
}
}
func TestAKeptVerdictIsAPassOfAPackageAtALevel(t *testing.T) {
t.Run("a preview is refused for what a reader of candidates could not place", previewIsRefused)
ok := checker.KeptByLevelDigestValue{State: VerdictPass, Repository: "novox/mesh-sdk", Package: "./go/keys", Level: LevelUnit, Toolchain: "1.26.0", At: "2026-11-05T10:00:00Z"}
if err := CheckKept(ok); err != nil {
t.Fatalf("a kept pass is refused: %v", err)
}
for name, edit := range map[string]func(*checker.KeptByLevelDigestValue){
"a fail": func(k *checker.KeptByLevelDigestValue) { k.State = VerdictFail },
"no owner": func(k *checker.KeptByLevelDigestValue) { k.Repository = "mesh-sdk" },
"no package": func(k *checker.KeptByLevelDigestValue) { k.Package = "" },
"an unknown level": func(k *checker.KeptByLevelDigestValue) { k.Level = "smoke" },
"negative tests": func(k *checker.KeptByLevelDigestValue) { k.Tests = -1 },
"no toolchain": func(k *checker.KeptByLevelDigestValue) { k.Toolchain = "" },
"no time": func(k *checker.KeptByLevelDigestValue) { k.At = "" },
} {
k := ok
edit(&k)
if CheckKept(k) == nil {
t.Errorf("%s was taken", name)
}
}
}
// A preview is refused for what a reader of candidates could not place.
func previewIsRefused(t *testing.T) {
good := func() checker.PreviewsByRepositoryHeadTrunkValue {
return checker.PreviewsByRepositoryHeadTrunkValue{Repository: "novox/a", Head: "h1", Trunk: "t1", Merge: "m1",
Modules: map[string]checker.PreviewsByRepositoryHeadTrunkValueModulesValue{"mod": {Tree: "tr", Manifest: strings.Repeat("a", 64),
Locks: map[string]string{"go.sum": "x"}, Paths: map[string]string{"src": "o1"}}}}
}
if err := CheckPreview(good()); err != nil {
t.Fatalf("a good preview is refused: %v", err)
}
for name, c := range map[string]struct {
edit func(*checker.PreviewsByRepositoryHeadTrunkValue)
says string
}{
"a repository with no owner": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) { p.Repository = "a" }, "<owner>/<name>"},
"a head with a dot": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) { p.Head = "h.1" }, "head"},
"a conflict with a merge": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) { p.Conflicts = []string{"f"} }, "in conflict"},
"no merge commit": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) { p.Merge = "" }, "no merge commit"},
"a module with no tree": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) {
m := p.Modules["mod"]
m.Tree = ""
p.Modules["mod"] = m
}, "no tree"},
"a short manifest digest": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) {
m := p.Modules["mod"]
m.Manifest = "abc"
p.Modules["mod"] = m
}, "manifest digest"},
"a path outside the module": {func(p *checker.PreviewsByRepositoryHeadTrunkValue) {
m := p.Modules["mod"]
m.Paths = map[string]string{"../x": "o"}
p.Modules["mod"] = m
}, "clean path"},
} {
p := good()
c.edit(&p)
if err := CheckPreview(p); err == nil || !strings.Contains(err.Error(), c.says) {
t.Errorf("%s: CheckPreview = %v, want it to say %q", name, err, c.says)
}
}
if err := CheckPreview(checker.PreviewsByRepositoryHeadTrunkValue{Repository: "novox/a", Head: "h", Trunk: "t", Conflicts: []string{"f"}}); err != nil {
t.Errorf("a head in conflict is refused: %v", err)
}
}
// A verdict's key as go/delivery's CheckerVerdictKey wrote it (golden): the group escaped, the heads hash after the
// last dot.
func TestVerdictKeyAsGoDeliveryWroteIt(t *testing.T) {
key, err := VerdictKey("fix/1.2", "0123456789ab")
if err != nil || key != "fix/1=2e2.0123456789ab" {
t.Fatalf("%q %v", key, err)
}
group, heads, err := ParseVerdictKey(key)
if err != nil || group != "fix/1.2" || heads != "0123456789ab" {
t.Fatalf("%q %q %v", group, heads, err)
}
for _, bad := range []string{"nodot", "g.XYZ", ".0123456789ab", "a.b.0123456789ab", "g=zz.0123456789ab"} {
if _, _, err := ParseVerdictKey(bad); err == nil {
t.Errorf("%q parses", bad)
}
}
if _, err := VerdictKey("", "0123456789ab"); err == nil {
t.Error("an empty group keys")
}
if _, err := VerdictKey("g", "0123"); err == nil {
t.Error("a short hash keys")
}
}
// The codecs write a value at the kept values' version after its rules and read it back through them.
func TestTheCodecsWriteAtTheVersionAndReadBackThroughTheRules(t *testing.T) {
raw, err := EncodeVerdict(passing())
if err != nil {
t.Fatal(err)
}
if got, err := DecodeVerdict(raw); err != nil || got.V == 0 || got.Group != "g" {
t.Errorf("verdict read back = %+v, %v", got, err)
}
bad := passing()
bad.Heads = "x"
if _, err := EncodeVerdict(bad); err == nil {
t.Error("a verdict whose heads are no hash is written")
}
if _, err := DecodeVerdict([]byte(`{"v":99,"group":"g","heads":"0123456789ab","state":"running"}`)); err == nil {
t.Error("a verdict of an unknown version is read")
}
k := checker.KeptByLevelDigestValue{State: VerdictPass, Repository: "novox/mesh-sdk", Package: "./go/keys", Level: LevelUnit, Toolchain: "1.26.0", At: "2026-11-05T10:00:00Z"}
raw, err = EncodeKept(k)
if err != nil {
t.Fatal(err)
}
if got, err := DecodeKept(raw); err != nil || got.Package != k.Package {
t.Errorf("kept read back = %+v, %v", got, err)
}
k.State = VerdictFail
if _, err := EncodeKept(k); err == nil {
t.Error("a failure is kept")
}
p := checker.PreviewsByRepositoryHeadTrunkValue{Repository: "novox/a", Head: "h1", Trunk: "t1", Conflicts: []string{"f.go"}}
raw, err = EncodePreview(p)
if err != nil {
t.Fatal(err)
}
if got, err := DecodePreview(raw); err != nil || got.Head != "h1" {
t.Errorf("preview read back = %+v, %v", got, err)
}
p.Conflicts = nil
if _, err := EncodePreview(p); err == nil {
t.Error("a preview with no merge commit and no conflict is written")
}
// 1921 (B0, G): a checking program's input is asked of the seat's verb input by its digest, and an answer for
// another digest, or bytes that are not the digest, is refused.
body := []byte(`{"v":1}`)
digest := DigestOf(body)
for name, c := range map[string]struct {
answer any
says string
}{
"its own bytes": {InputAnswerOf(body), ""},
"another digest": {checker.InputAnswer{Digest: DigestOf([]byte("x")), Input: InputAnswerOf(body).Input}, "answered the input"},
"bytes that are not it": {checker.InputAnswer{Digest: digest, Input: InputAnswerOf([]byte(`{"v":2}`)).Input}, "whose digest is"},
"bytes in no base64": {checker.InputAnswer{Digest: digest, Input: "%%"}, "no base64"},
"no answer of the layout": {"nothing", "answered no input"},
} {
got, err := ReadInput(func(key string, b any) (json.RawMessage, error) {
if key != "seat:mesh-delivery-checker.input" || b != (checker.InputInput{Digest: digest}) {
t.Errorf("%s: asked %s %+v", name, key, b)
}
return json.Marshal(c.answer)
}, digest)
switch {
case c.says == "" && (err != nil || string(got) != string(body)):
t.Errorf("%s: %q, %v", name, got, err)
case c.says != "" && (err == nil || !strings.Contains(err.Error(), c.says)):
t.Errorf("%s: %v, want a refusal saying %q", name, err, c.says)
}
}
}
// The kept and preview keys: a key reads back to its parts, and a part that does not key is refused.
func TestKeptAndPreviewKeysReadBack(t *testing.T) {
digest := strings.Repeat("ab", 32)
key, err := KeptKey(LevelUnit, digest)
if err != nil || key != "unit."+digest {
t.Fatalf("kept key = %q, %v", key, err)
}
if level, d, err := ParseKeptKey(key); err != nil || level != LevelUnit || d != digest {
t.Errorf("kept key read back = %q %q, %v", level, d, err)
}
for _, bad := range []string{"fast." + digest, "unit.XY", "unit"} {
if _, _, err := ParseKeptKey(bad); err == nil {
t.Errorf("kept key %q is read", bad)
}
}
key, err = PreviewKey("novox/mesh-sdk", "h1", "t1")
if err != nil {
t.Fatal(err)
}
if repo, h, tr, err := ParsePreviewKey(key); err != nil || repo != "novox/mesh-sdk" || h != "h1" || tr != "t1" {
t.Errorf("preview key %q read back = %q %q %q, %v", key, repo, h, tr, err)
}
for _, bad := range []string{"novox.h1.t1", "a/b.h1", "a/b.h1.t1.x"} {
if _, _, _, err := ParsePreviewKey(bad); err == nil {
t.Errorf("preview key %q is read", bad)
}
}
}
func judgedBy() checker.VerdictsByGroupHeadsValueJudgedBy {
const c = "0123456789abcdef0123456789abcdef01234567"
return checker.VerdictsByGroupHeadsValueJudgedBy{
Program: checker.VerdictsByGroupHeadsValueJudgedByProgram{Repository: "novox/mesh-delivery", Commit: c, Dir: "modules/mesh-delivery-checker", Package: "p"},
Key: "program-0123456789abcdef", Built: true, Heads: []checker.VerdictsByGroupHeadsValueJudgedByHeadsItem{{Repository: "novox/mesh-delivery", Commit: c}}}
}
@@ -1,150 +0,0 @@
package meshdeliverycheckerclient
import (
"encoding/json"
"fmt"
"strings"
checker "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// The codecs of the three states the checker writes and others read (the view and the gate read verdicts, the indexer reads
// previews, the checker and the tools read kept verdicts): a value is written at the version of the kept values after its rules
// (CheckVerdict, CheckKept, CheckPreview) and read back through the same rules. The checker's owed state is read by no other
// part and keeps its own codec.
// EncodeVerdict is v as JSON at the kept values' version, refused by CheckVerdict's rules.
func EncodeVerdict(v checker.VerdictsByGroupHeadsValue) ([]byte, error) {
if err := CheckVerdict(v); err != nil {
return nil, err
}
v.V = keys.Version
return json.Marshal(v)
}
// DecodeVerdict reads a `verdicts` value; it refuses an unknown version (keys.ErrUnknownVersion) and what EncodeVerdict refuses.
func DecodeVerdict(data []byte) (checker.VerdictsByGroupHeadsValue, error) {
var v checker.VerdictsByGroupHeadsValue
if err := decode(data, &v); err != nil {
return v, err
}
if err := CheckVerdict(v); err != nil {
return checker.VerdictsByGroupHeadsValue{}, err
}
return v, nil
}
// EncodeKept is k as JSON at the kept values' version, refused by CheckKept's rules.
func EncodeKept(k checker.KeptByLevelDigestValue) ([]byte, error) {
if err := CheckKept(k); err != nil {
return nil, err
}
k.V = keys.Version
return json.Marshal(k)
}
// DecodeKept reads a `kept` value; it refuses an unknown version and what EncodeKept refuses.
func DecodeKept(data []byte) (checker.KeptByLevelDigestValue, error) {
var k checker.KeptByLevelDigestValue
if err := decode(data, &k); err != nil {
return k, err
}
if err := CheckKept(k); err != nil {
return checker.KeptByLevelDigestValue{}, err
}
return k, nil
}
// EncodePreview is p as JSON at the kept values' version, refused by CheckPreview's rules.
func EncodePreview(p checker.PreviewsByRepositoryHeadTrunkValue) ([]byte, error) {
if err := CheckPreview(p); err != nil {
return nil, err
}
p.V = keys.Version
return json.Marshal(p)
}
// DecodePreview reads a `previews` value; it refuses an unknown version and what EncodePreview refuses.
func DecodePreview(data []byte) (checker.PreviewsByRepositoryHeadTrunkValue, error) {
var p checker.PreviewsByRepositoryHeadTrunkValue
if err := decode(data, &p); err != nil {
return p, err
}
if err := CheckPreview(p); err != nil {
return checker.PreviewsByRepositoryHeadTrunkValue{}, err
}
return p, nil
}
func decode(data []byte, into any) error {
if err := keys.CheckVersion(data); err != nil {
return err
}
if err := json.Unmarshal(data, into); err != nil {
return fmt.Errorf("meshdeliverycheckerclient: value does not fit its shape: %w", err)
}
return nil
}
// KeptKey is the key, in the state kept, of a kept verdict: `<level>.<digest>`, the level unit or integration and the digest,
// lowercase hex, of everything that package's tests read at that level as the language's build module names it.
func KeptKey(level, digest string) (string, error) {
if err := checkLevel(level); err != nil {
return "", err
}
if digest == "" || strings.Trim(digest, "0123456789abcdef") != "" {
return "", fmt.Errorf("meshdeliverycheckerclient: %q is not a digest, lowercase hex", digest)
}
return checker.KeptByLevelDigestKey(level, digest), nil
}
// ParseKeptKey is the inverse of KeptKey.
func ParseKeptKey(key string) (level, digest string, err error) {
level, digest, ok := checker.ParseKeptByLevelDigestKey(key)
if !ok {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a kept key, <level>.<digest>", key)
}
if _, err = KeptKey(level, digest); err != nil {
return "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a kept key: %w", key, err)
}
return level, digest, nil
}
// PreviewKey is the key, in the state previews, of a head merged onto a trunk commit: `<repository>.<head>.<trunk>`, the
// repository's owner and name each escaped (keys.EscapeName).
func PreviewKey(repository, head, trunk string) (string, error) {
if err := CheckRepository(repository); err != nil {
return "", err
}
if err := keys.CheckName("head", head); err != nil {
return "", err
}
if err := keys.CheckName("trunk commit", trunk); err != nil {
return "", err
}
owner, name, _ := strings.Cut(repository, "/")
return checker.PreviewsByRepositoryHeadTrunkKey(keys.EscapeName(owner)+"/"+keys.EscapeName(name), head, trunk), nil
}
// ParsePreviewKey is the inverse of PreviewKey.
func ParsePreviewKey(key string) (repository, head, trunk string, err error) {
repo, head, trunk, ok := checker.ParsePreviewsByRepositoryHeadTrunkKey(key)
if !ok || strings.Contains(trunk, ".") {
return "", "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a preview key, <repository>.<head>.<trunk>", key)
}
owner, name, found := strings.Cut(repo, "/")
if !found {
return "", "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a preview key: the repository has no slash", key)
}
owner, err1 := keys.UnescapeName(owner)
name, err2 := keys.UnescapeName(name)
if err1 != nil || err2 != nil {
return "", "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a preview key: the repository does not unescape", key)
}
repository = owner + "/" + name
if _, err := PreviewKey(repository, head, trunk); err != nil {
return "", "", "", fmt.Errorf("meshdeliverycheckerclient: %q is not a preview key: %w", key, err)
}
return repository, head, trunk, nil
}
@@ -1,8 +0,0 @@
module git.novox.be/novox/mesh-delivery/contracts/go/clients/meshdeliverycheckerclient
go 1.26.0
require (
git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
)
@@ -1,53 +0,0 @@
package meshdeliverycheckerclient
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
checker "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker"
)
// InputVerb is the seat's verb input as a manifest's `invokes` names it and a run ask's input names it: asked of the
// seat, on no one machine (novox/hq ADR 0644, ADR 0656; issue 1921). A checking program's input is kept by the checker
// by the sha256 of its exact bytes, and asked of it by the build module that runs the program (ADR 0596 §2).
const InputVerb = "seat:" + checker.Seat + "." + checker.VerbInput
// InputAnswerOf is the verb input's answer for body: its digest and its exact bytes, base64.
func InputAnswerOf(body []byte) checker.InputAnswer {
return checker.InputAnswer{Digest: DigestOf(body), Input: base64.StdEncoding.EncodeToString(body)}
}
// DigestOf is the digest a checking program's input is kept and asked by: the sha256 of its bytes, 64 lowercase hex
// digits.
func DigestOf(body []byte) string {
sum := sha256.Sum256(body)
return hex.EncodeToString(sum[:])
}
// ReadInput asks the verb input, with ask (a tools bundle's stdio.Ask, a process's Conn.Call), for the input kept by
// digest and answers its bytes, refusing an answer for another digest and bytes whose sha256 is not the digest.
func ReadInput(ask func(key string, body any) (json.RawMessage, error), digest string) ([]byte, error) {
const who = "meshdeliverycheckerclient: "
raw, err := ask(InputVerb, checker.InputInput{Digest: digest})
if err != nil {
return nil, fmt.Errorf(who+"asking %s for the input %s: %w", InputVerb, digest, err)
}
var a checker.InputAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf(who+"%s answered no input for %s: %w", InputVerb, digest, err)
}
if a.Digest != digest {
return nil, fmt.Errorf(who+"%s answered the input %q, asked %s", InputVerb, a.Digest, digest)
}
body, err := base64.StdEncoding.DecodeString(a.Input)
if err != nil {
return nil, fmt.Errorf(who+"%s answered the input %s in no base64: %w", InputVerb, digest, err)
}
if got := DigestOf(body); got != digest {
return nil, fmt.Errorf(who+"the input %s answered %d bytes whose digest is %s", digest, len(body), got)
}
return body, nil
}
@@ -1,490 +0,0 @@
// Code generated by seatgen from the seat definitions; DO NOT EDIT.
// Package meshdeliverychecker is the contract of the seat "mesh-delivery-checker", defined whole (seats/mesh-delivery-checker/seat.json): The merge check's tries: start one, read one, end one. The checker's own events stay under its own subjects (ADR 0620 §2).
package meshdeliverychecker
import (
"bytes"
"encoding/json"
"errors"
"strings"
)
// Seat is the seat's name.
const Seat = "mesh-delivery-checker"
const (
VerbTry = "try"
VerbTryRead = "try-read"
VerbTryEnd = "try-end"
VerbInput = "input"
)
// Verbs is every verb the seat serves, in its definition's order: a new copy each call.
func Verbs() []string {
return []string{VerbTry, VerbTryRead, VerbTryEnd, VerbInput}
}
// The holder's own events, listed beside the seat and published under the holder's subjects (ADR 0620 §2).
const (
HolderEventVerdict = "verdict"
HolderEventTagWanted = "tag-wanted"
HolderEventPreviewWritten = "preview.written"
)
// HolderSubjectVerdict is where the holder publishes verdict, kept in checker.asks.
func HolderSubjectVerdict(holder string) string { return "mesh.stream." + holder + ".event.verdict" }
// HolderSubjectTagWanted is where the holder publishes tag-wanted, kept in checker.asks.
func HolderSubjectTagWanted(holder string) string {
return "mesh.stream." + holder + ".event.tag-wanted"
}
// HolderSubjectPreviewWritten is where the holder publishes preview.written, kept in checks.
func HolderSubjectPreviewWritten(holder string) string {
return "mesh.stream." + holder + ".event.preview.written"
}
const (
StateVerdicts = "verdicts"
StateKept = "kept"
StateOwed = "owed"
StatePreviews = "previews"
)
// VerdictsByGroupHeadsKey is the key of one value of the state verdicts under the form "<group>.<heads>".
func VerdictsByGroupHeadsKey(group, heads string) string { return group + "." + heads }
// ParseVerdictsByGroupHeadsKey reads the parts of a key of the form "<group>.<heads>", in the order of the form; the last result is false for a key of another form.
func ParseVerdictsByGroupHeadsKey(key string) (string, string, bool) {
rest := key
v0, after0, found0 := strings.Cut(rest, ".")
if !found0 || v0 == "" {
return "", "", false
}
rest = after0
if rest == "" {
return "", "", false
}
v2 := rest
rest = ""
if rest != "" {
return "", "", false
}
return v0, v2, true
}
// DecodeVerdictsByGroupHeadsValue reads one value of the state verdicts under the form "<group>.<heads>", refusing a field VerdictsByGroupHeadsValue does not know and any text after the value.
func DecodeVerdictsByGroupHeadsValue(raw []byte) (VerdictsByGroupHeadsValue, error) {
var v VerdictsByGroupHeadsValue
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, err
}
if dec.More() {
return v, errors.New("text after the value")
}
return v, nil
}
// KeptByLevelDigestKey is the key of one value of the state kept under the form "<level>.<digest>".
func KeptByLevelDigestKey(level, digest string) string { return level + "." + digest }
// ParseKeptByLevelDigestKey reads the parts of a key of the form "<level>.<digest>", in the order of the form; the last result is false for a key of another form.
func ParseKeptByLevelDigestKey(key string) (string, string, bool) {
rest := key
v0, after0, found0 := strings.Cut(rest, ".")
if !found0 || v0 == "" {
return "", "", false
}
rest = after0
if rest == "" {
return "", "", false
}
v2 := rest
rest = ""
if rest != "" {
return "", "", false
}
return v0, v2, true
}
// DecodeKeptByLevelDigestValue reads one value of the state kept under the form "<level>.<digest>", refusing a field KeptByLevelDigestValue does not know and any text after the value.
func DecodeKeptByLevelDigestValue(raw []byte) (KeptByLevelDigestValue, error) {
var v KeptByLevelDigestValue
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, err
}
if dec.More() {
return v, errors.New("text after the value")
}
return v, nil
}
// OwedByRepositoryNumberHeadActKey is the key of one value of the state owed under the form "<repository>.<number>.<head>.<act>".
func OwedByRepositoryNumberHeadActKey(repository, number, head, act string) string {
return repository + "." + number + "." + head + "." + act
}
// ParseOwedByRepositoryNumberHeadActKey reads the parts of a key of the form "<repository>.<number>.<head>.<act>", in the order of the form; the last result is false for a key of another form.
func ParseOwedByRepositoryNumberHeadActKey(key string) (string, string, string, string, bool) {
rest := key
v0, after0, found0 := strings.Cut(rest, ".")
if !found0 || v0 == "" {
return "", "", "", "", false
}
rest = after0
v2, after2, found2 := strings.Cut(rest, ".")
if !found2 || v2 == "" {
return "", "", "", "", false
}
rest = after2
v4, after4, found4 := strings.Cut(rest, ".")
if !found4 || v4 == "" {
return "", "", "", "", false
}
rest = after4
if rest == "" {
return "", "", "", "", false
}
v6 := rest
rest = ""
if rest != "" {
return "", "", "", "", false
}
return v0, v2, v4, v6, true
}
// DecodeOwedByRepositoryNumberHeadActValue reads one value of the state owed under the form "<repository>.<number>.<head>.<act>", refusing a field OwedByRepositoryNumberHeadActValue does not know and any text after the value.
func DecodeOwedByRepositoryNumberHeadActValue(raw []byte) (OwedByRepositoryNumberHeadActValue, error) {
var v OwedByRepositoryNumberHeadActValue
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, err
}
if dec.More() {
return v, errors.New("text after the value")
}
return v, nil
}
// PreviewsByRepositoryHeadTrunkKey is the key of one value of the state previews under the form "<repository>.<head>.<trunk>".
func PreviewsByRepositoryHeadTrunkKey(repository, head, trunk string) string {
return repository + "." + head + "." + trunk
}
// ParsePreviewsByRepositoryHeadTrunkKey reads the parts of a key of the form "<repository>.<head>.<trunk>", in the order of the form; the last result is false for a key of another form.
func ParsePreviewsByRepositoryHeadTrunkKey(key string) (string, string, string, bool) {
rest := key
v0, after0, found0 := strings.Cut(rest, ".")
if !found0 || v0 == "" {
return "", "", "", false
}
rest = after0
v2, after2, found2 := strings.Cut(rest, ".")
if !found2 || v2 == "" {
return "", "", "", false
}
rest = after2
if rest == "" {
return "", "", "", false
}
v4 := rest
rest = ""
if rest != "" {
return "", "", "", false
}
return v0, v2, v4, true
}
// DecodePreviewsByRepositoryHeadTrunkValue reads one value of the state previews under the form "<repository>.<head>.<trunk>", refusing a field PreviewsByRepositoryHeadTrunkValue does not know and any text after the value.
func DecodePreviewsByRepositoryHeadTrunkValue(raw []byte) (PreviewsByRepositoryHeadTrunkValue, error) {
var v PreviewsByRepositoryHeadTrunkValue
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, err
}
if dec.More() {
return v, errors.New("text after the value")
}
return v, nil
}
// TryInputMembersItem is a type of the contract.
type TryInputMembersItem struct {
// the full commit to try, 40 or 64 hex digits
Head string `json:"head"`
// <owner>/<name>
Repository string `json:"repository"`
// the trunk commit to merge it onto, or the trunk's branch for its head now; the trunk's head when absent
Trunk string `json:"trunk,omitempty"`
}
// TryInput is what try takes.
type TryInput struct {
// the full commit to try, 40 or 64 hex digits, for a try of one member (instead of members)
Head string `json:"head,omitempty"`
// unit or integration: only this level; both when absent
Level string `json:"level,omitempty"`
// the group: one repository at most once, each at the exact commit asked and the trunk commit it is merged onto; instead of repository and head
Members []TryInputMembersItem `json:"members,omitempty"`
// <owner>/<name>, for a try of one member (instead of members)
Repository string `json:"repository,omitempty"`
// a go test -run pattern: only those tests run, and nothing is kept
Tests string `json:"tests,omitempty"`
// the trunk commit to merge it onto, or the trunk's branch for its head now; the trunk's head when absent
Trunk string `json:"trunk,omitempty"`
}
// TryAnswer is what try answers.
type TryAnswer struct {
// the try's id
ID string `json:"id"`
// its state
State string `json:"state,omitempty"`
}
// TryReadInput is what try-read takes.
type TryReadInput struct {
// the try's id, try-<digits>
ID string `json:"id"`
}
// TryReadAnswer is what try-read answers.
type TryReadAnswer = map[string]any
// TryEndInput is what try-end takes.
type TryEndInput struct {
// the try's id, try-<digits>
ID string `json:"id"`
// why it is ended, in words
Why string `json:"why"`
}
// TryEndAnswer is what try-end answers.
type TryEndAnswer struct {
// it is ended
Ended bool `json:"ended"`
// the try
ID string `json:"id"`
}
// InputInput is what input takes.
type InputInput struct {
// the input's sha256, 64 lowercase hex digits, as the run ask names it
Digest string `json:"digest"`
}
// InputAnswer is what input answers.
type InputAnswer struct {
// the digest asked
Digest string `json:"digest"`
// the input's exact bytes, base64, so no encoding on the way changes a byte the digest covers
Input string `json:"input"`
}
// VerdictHolderEventSeriesItem is a type of the contract.
type VerdictHolderEventSeriesItem struct {
// its artifact, or the package's ecosystem name as the module's packages name it
Artifact string `json:"artifact"`
// the series on trunk
From string `json:"from"`
// the module whose artifact's series changes
Module string `json:"module"`
// the series the checked head gives it
To string `json:"to"`
}
// VerdictHolderEvent is the body of the holder's event verdict.
type VerdictHolderEvent struct {
// the commit checked
Head string `json:"head"`
// the generated files out of step with their seat definitions, each path (design 26)
OutOfStep []string `json:"out-of-step,omitempty"`
// the pull request's number, for a pull request's check
Pull int64 `json:"pull,omitempty"`
// owner/repo
Repository string `json:"repository"`
// each change of an artifact's series the checked head makes against trunk's manifests, once each (design 32); absent when it changes none
Series []VerdictHolderEventSeriesItem `json:"series,omitempty"`
// pass or fail
Verdict string `json:"verdict"`
}
// TagWantedHolderEvent is the body of the holder's event tag-wanted.
type TagWantedHolderEvent struct {
// the pull request's branch: its tag is removed when the branch ends
Branch string `json:"branch"`
// its head
Head string `json:"head"`
// the group member
Module string `json:"module"`
// the package it declares
Package string `json:"package"`
// the pull request
Pull int64 `json:"pull,omitempty"`
// owner/repo
Repository string `json:"repository"`
// the tag wanted
Tag string `json:"tag,omitempty"`
}
// VerdictsByGroupHeadsValueComposition is a type of the contract.
type VerdictsByGroupHeadsValueComposition struct {
Fpset string `json:"fpset,omitempty"`
Machines []string `json:"machines,omitempty"`
Sdk string `json:"sdk,omitempty"`
// not-run, pass or fail
State string `json:"state"`
Words string `json:"words,omitempty"`
}
// VerdictsByGroupHeadsValueFailed is a type of the contract.
type VerdictsByGroupHeadsValueFailed struct {
Machine string `json:"machine,omitempty"`
Test string `json:"test,omitempty"`
Words string `json:"words,omitempty"`
}
// VerdictsByGroupHeadsValueFailuresItem is a type of the contract.
type VerdictsByGroupHeadsValueFailuresItem struct {
Machine string `json:"machine,omitempty"`
Test string `json:"test,omitempty"`
Words string `json:"words,omitempty"`
}
// VerdictsByGroupHeadsValueJudgedByHeadsItem is a type of the contract.
type VerdictsByGroupHeadsValueJudgedByHeadsItem struct {
Commit string `json:"commit"`
Repository string `json:"repository"`
}
// VerdictsByGroupHeadsValueJudgedByProgram is a type of the contract.
type VerdictsByGroupHeadsValueJudgedByProgram struct {
Commit string `json:"commit"`
Dir string `json:"dir"`
Package string `json:"package"`
Repository string `json:"repository"`
}
// VerdictsByGroupHeadsValueJudgedBy is the checking program that judged the check: where it was built, the key its build is kept under, whether this check's run built it, and the heads it read (ADR 0644, ADR 0656). Absent in a value written before it.
type VerdictsByGroupHeadsValueJudgedBy struct {
Built bool `json:"built,omitempty"`
Heads []VerdictsByGroupHeadsValueJudgedByHeadsItem `json:"heads"`
// program- and 16 hex digits
Key string `json:"key"`
Program VerdictsByGroupHeadsValueJudgedByProgram `json:"program"`
}
// VerdictsByGroupHeadsValueLevelsValue is a type of the contract.
type VerdictsByGroupHeadsValueLevelsValue struct {
Kept int64 `json:"kept"`
Run int64 `json:"run"`
Skipped int64 `json:"skipped,omitempty"`
}
// VerdictsByGroupHeadsValueSeriesItem is a type of the contract.
type VerdictsByGroupHeadsValueSeriesItem struct {
Artifact string `json:"artifact"`
From string `json:"from"`
Module string `json:"module"`
To string `json:"to"`
}
// VerdictsByGroupHeadsValueTook is milliseconds.
type VerdictsByGroupHeadsValueTook struct {
Clone int64 `json:"clone,omitempty"`
Composition int64 `json:"composition,omitempty"`
IntegrationRun int64 `json:"integration-run,omitempty"`
IntegrationSetup int64 `json:"integration-setup,omitempty"`
Lint int64 `json:"lint,omitempty"`
Queue int64 `json:"queue,omitempty"`
Unit int64 `json:"unit,omitempty"`
}
// VerdictsByGroupHeadsValue is one value of the state verdicts under the key <group>.<heads>.
type VerdictsByGroupHeadsValue struct {
Beside map[string]string `json:"beside,omitempty"`
CarriedFrom map[string]string `json:"carried-from,omitempty"`
Composition *VerdictsByGroupHeadsValueComposition `json:"composition,omitempty"`
Failed *VerdictsByGroupHeadsValueFailed `json:"failed,omitempty"`
Failures []VerdictsByGroupHeadsValueFailuresItem `json:"failures,omitempty"`
Group string `json:"group"`
// 12 hex digits
Heads string `json:"heads"`
// the checking program that judged the check: where it was built, the key its build is kept under, whether this check's run built it, and the heads it read (ADR 0644, ADR 0656). Absent in a value written before it
JudgedBy *VerdictsByGroupHeadsValueJudgedBy `json:"judged-by,omitempty"`
// by level, unit or integration
Levels map[string]VerdictsByGroupHeadsValueLevelsValue `json:"levels,omitempty"`
Machines []string `json:"machines,omitempty"`
OverBound []string `json:"over-bound,omitempty"`
Sdk string `json:"sdk,omitempty"`
Series []VerdictsByGroupHeadsValueSeriesItem `json:"series,omitempty"`
// running, pass or fail
State string `json:"state"`
// milliseconds
Took *VerdictsByGroupHeadsValueTook `json:"took,omitempty"`
// repository to the trunk head merged onto
Trunk map[string]string `json:"trunk,omitempty"`
// the layout version
V int64 `json:"v,omitempty"`
}
// KeptByLevelDigestValue is one value of the state kept under the key <level>.<digest>.
type KeptByLevelDigestValue struct {
// when (RFC 3339 time)
At string `json:"at,omitempty"`
Level string `json:"level"`
Package string `json:"package"`
Repository string `json:"repository"`
// pass: a failure is never kept
State string `json:"state"`
Tests int64 `json:"tests,omitempty"`
Took int64 `json:"took,omitempty"`
Toolchain string `json:"toolchain,omitempty"`
// the layout version
V int64 `json:"v,omitempty"`
}
// OwedByRepositoryNumberHeadActValue is one value of the state owed under the key <repository>.<number>.<head>.<act>.
type OwedByRepositoryNumberHeadActValue struct {
// status=<context>, view, note or comment.<seq>
Act string `json:"act"`
Context string `json:"context,omitempty"`
Ref string `json:"ref,omitempty"`
State string `json:"state,omitempty"`
Target string `json:"target,omitempty"`
Text string `json:"text,omitempty"`
// the layout version
V int64 `json:"v,omitempty"`
}
// PreviewsByRepositoryHeadTrunkValueModulesValue is a type of the contract.
type PreviewsByRepositoryHeadTrunkValueModulesValue struct {
Locks map[string]string `json:"locks,omitempty"`
// manifest digest
Manifest string `json:"manifest"`
Packages []string `json:"packages,omitempty"`
Paths map[string]string `json:"paths,omitempty"`
Tree string `json:"tree"`
}
// PreviewsByRepositoryHeadTrunkValue is one value of the state previews under the key <repository>.<head>.<trunk>.
type PreviewsByRepositoryHeadTrunkValue struct {
// files in conflict
Conflicts []string `json:"conflicts,omitempty"`
Head string `json:"head"`
// the merge commit
Merge string `json:"merge,omitempty"`
// by directory
Modules map[string]PreviewsByRepositoryHeadTrunkValueModulesValue `json:"modules,omitempty"`
Repository string `json:"repository"`
Trunk string `json:"trunk"`
// the layout version
V int64 `json:"v,omitempty"`
}
@@ -1,82 +0,0 @@
// Code generated by seatgen from the seat definitions; DO NOT EDIT.
package meshdeliverychecker
import (
"encoding/json"
"reflect"
"regexp"
"testing"
)
// TestFixtures reads every fixture of seats/mesh-delivery-checker/fixtures: each decodes into its type, a field the type does not
// know is dropped (ADR 0608 §6), and it reads back as its wire says; each subject named is the contract's.
func TestFixtures(t *testing.T) {
cases := []struct {
name, subject, given, wire string
decode func([]byte) (any, error)
subjectIs *regexp.Regexp
}{
{name: "verdict on the checker's own family", subject: "mesh.stream.mesh-delivery-checker.event.verdict", given: "{\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"out-of-step\":[\"go/seats/meshbroker/contract.go\"],\"pull\":3,\"repository\":\"novox/mesh-contracts\",\"series\":[{\"artifact\":\"go\",\"from\":\"0.1\",\"module\":\"mesh-contracts\",\"to\":\"0.2\"}],\"verdict\":\"fail\"}", wire: "{\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"out-of-step\":[\"go/seats/meshbroker/contract.go\"],\"pull\":3,\"repository\":\"novox/mesh-contracts\",\"series\":[{\"artifact\":\"go\",\"from\":\"0.1\",\"module\":\"mesh-contracts\",\"to\":\"0.2\"}],\"verdict\":\"fail\"}",
decode: func(b []byte) (any, error) { var v VerdictHolderEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.stream\\.[a-z0-9-]+\\.event\\.verdict$")},
{name: "tag-wanted on the checker's own family", subject: "mesh.stream.mesh-delivery-checker.event.tag-wanted", given: "{\"branch\":\"feat/registry\",\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"module\":\"mesh-sdk\",\"package\":\"go\",\"pull\":170,\"repository\":\"novox/mesh-sdk\",\"tag\":\"registry-1966\"}", wire: "{\"branch\":\"feat/registry\",\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"module\":\"mesh-sdk\",\"package\":\"go\",\"pull\":170,\"repository\":\"novox/mesh-sdk\",\"tag\":\"registry-1966\"}",
decode: func(b []byte) (any, error) { var v TagWantedHolderEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.stream\\.[a-z0-9-]+\\.event\\.tag-wanted$")},
{name: "preview.written on the checker's stream", subject: "mesh.stream.mesh-delivery-checker.event.preview.written", given: "{}", wire: "{}",
decode: func(b []byte) (any, error) { var v map[string]any; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.stream\\.[a-z0-9-]+\\.event\\.preview\\.written$")},
{name: "a running verdict", subject: "", given: "{\"group\":\"feat/registry\",\"heads\":\"0123456789ab\",\"state\":\"running\",\"v\":1}", wire: "{\"group\":\"feat/registry\",\"heads\":\"0123456789ab\",\"state\":\"running\",\"v\":1}",
decode: func(b []byte) (any, error) {
var v VerdictsByGroupHeadsValue
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "a pass judged by the checking program built at a mesh-delivery head", subject: "", given: "{\"group\":\"feat/registry\",\"heads\":\"0123456789ab\",\"judged-by\":{\"built\":true,\"heads\":[{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"repository\":\"novox/mesh-delivery\"}],\"key\":\"program-0123456789abcdef\",\"program\":{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"dir\":\"modules/mesh-delivery-checker\",\"package\":\"./cmd/mesh-checking-program\",\"repository\":\"novox/mesh-delivery\"}},\"levels\":{\"integration\":{\"kept\":0,\"run\":3},\"unit\":{\"kept\":0,\"run\":12}},\"state\":\"pass\",\"v\":1}", wire: "{\"group\":\"feat/registry\",\"heads\":\"0123456789ab\",\"judged-by\":{\"built\":true,\"heads\":[{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"repository\":\"novox/mesh-delivery\"}],\"key\":\"program-0123456789abcdef\",\"program\":{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"dir\":\"modules/mesh-delivery-checker\",\"package\":\"./cmd/mesh-checking-program\",\"repository\":\"novox/mesh-delivery\"}},\"levels\":{\"integration\":{\"kept\":0,\"run\":3},\"unit\":{\"kept\":0,\"run\":12}},\"state\":\"pass\",\"v\":1}",
decode: func(b []byte) (any, error) {
var v VerdictsByGroupHeadsValue
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "a kept pass", subject: "", given: "{\"at\":\"2026-11-05T10:00:00Z\",\"level\":\"unit\",\"package\":\"go/keys\",\"repository\":\"novox/mesh-sdk\",\"state\":\"pass\",\"tests\":4,\"took\":120,\"toolchain\":\"go1.26\",\"v\":1}", wire: "{\"at\":\"2026-11-05T10:00:00Z\",\"level\":\"unit\",\"package\":\"go/keys\",\"repository\":\"novox/mesh-sdk\",\"state\":\"pass\",\"tests\":4,\"took\":120,\"toolchain\":\"go1.26\",\"v\":1}",
decode: func(b []byte) (any, error) { var v KeptByLevelDigestValue; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "the status owed for a head", subject: "", given: "{\"act\":\"status=mesh/check\",\"context\":\"mesh/check\",\"state\":\"success\",\"v\":1}", wire: "{\"act\":\"status=mesh/check\",\"context\":\"mesh/check\",\"state\":\"success\",\"v\":1}",
decode: func(b []byte) (any, error) {
var v OwedByRepositoryNumberHeadActValue
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "a preview", subject: "", given: "{\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"merge\":\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\",\"repository\":\"novox/mesh-sdk\",\"trunk\":\"dddddddddddddddddddddddddddddddddddddddd\",\"v\":1}", wire: "{\"head\":\"cccccccccccccccccccccccccccccccccccccccc\",\"merge\":\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\",\"repository\":\"novox/mesh-sdk\",\"trunk\":\"dddddddddddddddddddddddddddddddddddddddd\",\"v\":1}",
decode: func(b []byte) (any, error) {
var v PreviewsByRepositoryHeadTrunkValue
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "a checking program asks its input by its digest", subject: "", given: "{\"digest\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}", wire: "{\"digest\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}",
decode: func(b []byte) (any, error) { var v InputInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "the input answered as its exact bytes, base64", subject: "", given: "{\"digest\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\",\"input\":\"eyJ2IjoxfQ==\"}", wire: "{\"digest\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\",\"input\":\"eyJ2IjoxfQ==\"}",
decode: func(b []byte) (any, error) { var v InputAnswer; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
}
for _, c := range cases {
v, err := c.decode([]byte(c.given))
if err != nil {
t.Errorf("%s: does not decode: %v", c.name, err)
continue
}
back, err := json.Marshal(v)
if err != nil {
t.Errorf("%s: does not encode: %v", c.name, err)
continue
}
var got, want any
if err := json.Unmarshal(back, &got); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(c.wire), &want); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("%s: reads back as %s, want %s", c.name, back, c.wire)
}
if c.subjectIs != nil && !c.subjectIs.MatchString(c.subject) {
t.Errorf("%s: subject %q is not the contract's %s", c.name, c.subject, c.subjectIs)
}
}
}
@@ -1,3 +0,0 @@
module git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdeliverychecker
go 1.26.0
@@ -1,237 +0,0 @@
package main
import (
"context"
"maps"
"slices"
"strings"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"mesh-delivery-assigner/internal/acting"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assigngraph"
"mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
)
// The waits for an acting part's new version in the steps the assigner holds (design 47 G §266, §268, §276): an entry of the assignment
// graph whose acting edge names composing or placing waits, its want held, until the part's version runs on the edge's node. The wait is
// kept in the state `waits` under `acting.<node>.<module>.<part>`, said as `wait-held` when it starts and `wait-ended` (ran, released,
// replaced) when it ends; `assigner_waits` reads it and `assigner_release` with how `now` lets the entry move with the part's running
// version. A node away starts no wait: its clock starts when the node is present (§268).
// actingOf is the Module.Acting of module: the held acting edges of its entry on a node, those whose wait was not released left out.
func (p *passer) actingOf(module string, released map[string]bool) func(node string) []assign.ActingEdge {
return func(node string) []assign.ActingEdge {
var out []assign.ActingEdge
if p.engineOn(node) == module {
return nil // the node-engine's own want is held by no acting edge, so it is written first (§268, A-323, A-330)
}
for _, e := range p.entryEdges(node, module) {
if acting.Held(e.Step) && !released[acting.Key(node, module, e.Module)+"@"+e.Fp] {
out = append(out, assign.ActingEdge{Node: e.Node, Part: e.Module, Fp: e.Fp, Step: e.Step, Seat: e.Seat})
}
}
return out
}
}
// engineOn is the module that holds the seat node-engine on node in the revision the pass computed, read from the acting edges'
// seat (A-330); "" when none is read.
func (p *passer) engineOn(node string) string {
if p.graph == nil {
return ""
}
return assigngraph.Engines(slices.Collect(maps.Values(p.graph.computed.Entries)))[node]
}
// entryEdges are the acting edges of the entry of module on node in the revision the pass computed.
func (p *passer) entryEdges(node, module string) []seat.Edge {
g := p.graph
if g == nil {
return nil
}
for _, ref := range g.computed.Revision.Entries {
if ref.Node == node && ref.Module == module {
var out []seat.Edge
for _, e := range g.computed.Entries[ref.Digest].Edges {
if e.Kind == "acting" {
out = append(out, e)
}
}
return out
}
}
return nil
}
// actingReleased is the waits released by hand and not yet run, by `<key>@<part's fingerprint>`.
func (p *passer) actingReleased() map[string]bool {
out := map[string]bool{}
for key, raw := range p.w.read(buckets.Waits()) {
if w, err := acting.Decode(raw); err == nil && w.Released && (acting.Is(key) || acting.IsOrder(key)) {
out[key+"@"+w.Fp] = true
}
}
return out
}
// actingWaits keeps the acting waits after the pass's wants: it starts the wait of each entry held for a part's version, ends the
// wait of one that ran, was replaced or was released, and says each.
func (p *passer) actingWaits(ctx context.Context, n assign.Nodes, wanted map[string]map[string]meshwants.Want) {
g := p.graph
if g == nil || p.kvs[buckets.Waits()] == nil {
return
}
now := p.clock()
kept := p.w.read(buckets.Waits())
standing := map[string]bool{}
engines := assigngraph.Engines(slices.Collect(maps.Values(g.computed.Entries)))
held := map[string]bool{} // `<node>/<module>` of each entry held for a part's version
for _, ref := range g.computed.Revision.Entries {
entry := g.computed.Entries[ref.Digest]
if w, ok := wanted[ref.Module][ref.Node]; ok && w.Fp == entry.Fp {
continue // the entry's version is wanted already: nothing moves, so nothing waits
}
if engines[ref.Node] == ref.Module {
continue // the node-engine's own want waits for no acting part (§268, A-323, A-330)
}
for _, e := range entry.Edges {
if e.Kind != "acting" || !acting.Held(e.Step) {
continue
}
key := acting.Key(ref.Node, ref.Module, e.Module)
if took, runs := n.ActingRuns(assign.ActingEdge{Node: e.Node, Part: e.Module, Fp: e.Fp, Step: e.Step, Seat: e.Seat}); runs {
if took != e.Fp && kept[key] != nil {
p.logf("the wait of %s on %s for %s ends: %s runs %s, which serves the seat %s, though its newest is %s (design 47 G A-426)", ref.Module, ref.Node, e.Module, e.Node, took, e.Seat, e.Fp)
}
continue
}
standing[key] = true
held[ref.Node+"/"+ref.Module] = true
if raw := kept[key]; raw != nil {
if w, err := acting.Decode(raw); err == nil && w.Entry == entry.Fp && w.Fp == e.Fp {
p.actingReleaseSaid(ctx, key, w)
continue
}
}
if !n.Online[ref.Node] {
continue // a node away holds only itself, and its clock has not started (§268)
}
w := acting.Wait{Step: e.Step, Node: ref.Node, Module: ref.Module, Part: e.Module, PartNode: e.Node, Fp: e.Fp, Entry: entry.Fp,
Since: now, ClockFrom: now, Bound: acting.BoundOf(e).String()}
if err := p.wantsSay(seat.EventWaitHeld, acting.Body(w, assignment.Module()), key+"."+e.Fp+"."+entry.Fp); err != nil {
p.logf("the wait of %s on %s for %s is not said, and is said at the next pass: %v", ref.Module, ref.Node, e.Module, err)
continue
}
p.put(ctx, buckets.Waits(), key, func() ([]byte, error) { return acting.Encode(w) })
p.logf("the want of %s on %s is held: its acting part %s (step %s) does not run the version %s on %s; the wait %s ends when it does, or by assigner_release", ref.Module, ref.Node, e.Module, e.Step, e.Fp, e.Node, key)
}
}
p.actingCycles(g.computed.Entries, engines, held, n)
for key, raw := range kept {
if !acting.Is(key) || standing[key] {
continue
}
w, err := acting.Decode(raw)
if err != nil {
continue
}
how := acting.HowRan
if w.Released {
how = acting.HowReleased
} else if e, ok := p.edgeOf(w); !ok {
how = acting.HowReplaced
} else if _, runs := n.ActingRuns(e); !runs {
how = acting.HowReplaced
}
if !w.EndSaid {
body := acting.Body(w, assignment.Module())
body.How = how
if err := p.wantsSay(seat.EventWaitEnded, body, key+"."+w.Fp+"."+w.Entry+"."+how); err != nil {
p.logf("the end of the wait of %s on %s for %s is not said, and is said at the next pass: %v", w.Module, w.Node, w.Part, err)
continue
}
}
p.remove(ctx, buckets.Waits(), key)
}
}
// actingReleaseSaid says wait-ended of a wait released by hand, once, and keeps its record so the entry is not held again.
func (p *passer) actingReleaseSaid(ctx context.Context, key string, w acting.Wait) {
if !w.Released || w.EndSaid {
return
}
body := acting.Body(w, assignment.Module())
body.How = acting.HowReleased
body.By = w.By
if err := p.wantsSay(seat.EventWaitEnded, body, key+"."+w.Fp+"."+w.Entry+"."+acting.HowReleased); err != nil {
p.logf("the release of the wait of %s on %s for %s is not said, and is said at the next pass: %v", w.Module, w.Node, w.Part, err)
return
}
w.EndSaid = true
p.put(ctx, buckets.Waits(), key, func() ([]byte, error) { return acting.Encode(w) })
}
// edgeOf is the edge a kept wait stands on, as an acting edge.
func (p *passer) edgeOf(w acting.Wait) (assign.ActingEdge, bool) {
return assign.ActingEdge{Node: w.PartNode, Part: w.Part, Fp: w.Fp, Step: w.Step}, true
}
// actingCycles writes the finding acting-cycle of each held want whose holding edges lie on a cycle no rule breaks, and clears it of
// every other want, a finding a pass before or another process wrote included (design 47 G A-323, A-330). An edge holds while its
// step is the assigner's, its part's version does not run and its wait was not released; the node-engine's own want is held by none.
func (p *passer) actingCycles(entries map[string]seat.AssignmentEntry, engines map[string]string, held map[string]bool, n assign.Nodes) {
if p.findings.Put == nil {
return
}
released := p.actingReleased()
cycles := assigngraph.HeldCycles(slices.Collect(maps.Values(entries)), func(e seat.AssignmentEntry, edge seat.Edge) bool {
return held[e.Node+"/"+e.Module] && engines[e.Node] != e.Module && edge.Kind == "acting" && acting.Held(edge.Step) &&
!released[acting.Key(e.Node, e.Module, edge.Module)+"@"+edge.Fp] && !actingRunsOf(n, edge)
})
raised := map[string]bool{}
for _, at := range slices.Sorted(maps.Keys(cycles)) {
node, module, _ := strings.Cut(at, "/")
o := assign.ActingCycleFinding(node, module, cycles[at])
key := mcseatKey(o)
raised[key] = true
if p.said[key+"="+o.Summary] {
continue // written already as it stands
}
if err := p.findings.Put(o.Finding(p.clock())); err != nil {
p.logf("the finding %s is not written: %v", key, err)
continue
}
p.said[key+"="+o.Summary] = true
}
if p.findings.Keys == nil || p.findings.Delete == nil {
return
}
keys, err := p.findings.Keys()
if err != nil {
p.logf("the findings %s are not read, so none is cleared this pass: %v", assign.KindActingCycle, err)
return
}
for _, key := range keys {
if strings.HasSuffix(key, "."+assign.KindActingCycle) && !raised[key] {
if err := p.findings.Delete(key); err != nil {
p.logf("the finding %s is not cleared: %v", key, err)
continue
}
for said := range p.said {
if strings.HasPrefix(said, key+"=") {
delete(p.said, said)
}
}
}
}
}
// actingRunsOf says whether an assignment edge's acting part runs a build serving it (A-426).
func actingRunsOf(n assign.Nodes, edge seat.Edge) bool {
_, runs := n.ActingRuns(assign.ActingEdge{Node: edge.Node, Part: edge.Module, Fp: edge.Fp, Step: edge.Step, Seat: edge.Seat})
return runs
}
@@ -1,186 +0,0 @@
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"mesh-delivery-assigner/internal/acting"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/buckets"
)
// Design 47 G §266, §268, §276 (AS9): an entry with an acting edge in composing waits for the part's version to run on the edge's node;
// the wait is kept, said as wait-held with its bound and clock-from, read by assigner_waits, released by assigner_release with how
// `now` and ended when the version runs.
func TestAnEntryWaitsForItsActingPartAndTheWaitIsKeptSaidAndEnded(t *testing.T) {
now := time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
p := newPasser(kvSet{buckets.Waits(): &memKV{values: map[string][]byte{}}}, now)
var events []string
var bodies []meshwants.Wait
p.publishWants = func(event string, body any, id string) error {
events = append(events, event)
bodies = append(bodies, body.(meshwants.Wait))
return nil
}
entry := meshwants.AssignmentEntry{Node: "ace", Module: "nats", Fp: fpTest, Edges: []meshwants.Edge{
{Kind: "acting", Node: "ace", Module: "mesh-host", Fp: "src2:new", Seat: "node-engine", Step: "compose", Bound: "15m"},
{Kind: "acting", Node: "ace", Module: "indexer", Fp: "src2:idx", Seat: "mesh-catalog", Step: "take-in"}}}
p.graph = &graphKeeper{}
p.graph.computed.Revision.Entries = []meshwants.NodeEntryRef{{Node: "ace", Module: "nats", Digest: "d1"}}
p.graph.computed.Entries = map[string]meshwants.AssignmentEntry{"d1": entry}
// The old build of mesh-host serves no seat of the edge here, so the entry waits (A-426: one serving it ends the wait).
notServing := func(nodeengine.Running, string) (bool, bool) { return false, true }
n := assign.Nodes{Online: map[string]bool{"ace": true}, Running: map[string]map[string]nodeengine.Running{"ace": {"mesh-host": {Fingerprint: "src2:old"}}}, Serves: notServing}
wanted := map[string]map[string]mwc.Want{"nats": {"ace": {Fp: "src2:older"}}}
ctx := context.Background()
if got := p.actingOf("nats", nil)("ace"); len(got) != 1 || got[0].Part != "mesh-host" {
t.Fatalf("the assigner holds composing only: %+v", got)
}
p.actingWaits(ctx, n, wanted)
p.actingWaits(ctx, n, wanted) // said once
if len(events) != 1 || events[0] != meshwants.EventWaitHeld {
t.Fatalf("events %v", events)
}
b := bodies[0]
if b.Step != "compose" || b.Part != "mesh-host" || b.Fp != "src2:new" || b.Bound != "15m0s" || b.ClockFrom == nil || !b.ClockFrom.Equal(now) || b.Owner == "" {
t.Errorf("wait-held %+v", b)
}
key := acting.Key("ace", "nats", "mesh-host")
if _, err := acting.Decode(p.w.read(buckets.Waits())[key]); err != nil {
t.Fatalf("the wait is kept: %v", err)
}
// a release by hand lets the entry move, and ends the wait once
w, _ := acting.Decode(p.w.read(buckets.Waits())[key])
w.Released = true
raw, _ := acting.Encode(w)
p.w.put(buckets.Waits(), key, raw)
if got := p.actingOf("nats", p.actingReleased())("ace"); len(got) != 0 {
t.Errorf("a released wait still holds: %+v", got)
}
p.actingWaits(ctx, n, wanted)
p.actingWaits(ctx, n, wanted)
if len(events) != 2 || events[1] != meshwants.EventWaitEnded || bodies[1].How != acting.HowReleased {
t.Fatalf("events %v bodies %+v", events, bodies)
}
// the version runs: the record goes, said nothing more
n.Running["ace"]["mesh-host"] = nodeengine.Running{Fingerprint: "src2:new"}
p.actingWaits(ctx, n, wanted)
if len(p.w.read(buckets.Waits())) != 0 || len(events) != 2 {
t.Errorf("kept %v events %v", p.w.read(buckets.Waits()), events)
}
}
func TestAnActingWaitOfANodeAwayStartsNoClockAndAnEntryWantedAlreadyWaitsNot(t *testing.T) {
p := newPasser(kvSet{buckets.Waits(): &memKV{values: map[string][]byte{}}}, time.Now())
p.publishWants = func(string, any, string) error { t.Fatal("said"); return nil }
p.graph = &graphKeeper{}
p.graph.computed.Revision.Entries = []meshwants.NodeEntryRef{{Node: "ace", Module: "nats", Digest: "d1"}}
p.graph.computed.Entries = map[string]meshwants.AssignmentEntry{"d1": {Node: "ace", Module: "nats", Fp: "src2:a", Edges: []meshwants.Edge{
{Kind: "acting", Node: "ace", Module: "mesh-host", Fp: "src2:new", Step: "compose"}}}}
n := assign.Nodes{Online: map[string]bool{}}
p.actingWaits(context.Background(), n, map[string]map[string]mwc.Want{})
n.Online["ace"] = true
p.actingWaits(context.Background(), n, map[string]map[string]mwc.Want{"nats": {"ace": {Fp: "src2:a"}}})
if len(p.w.read(buckets.Waits())) != 0 || strings.Contains(p.graph.computed.Entries["d1"].Fp, "x") {
t.Errorf("kept %v", p.w.read(buckets.Waits()))
}
}
func TestTheToolsReadAndReleaseAnActingWait(t *testing.T) {
var acts []string
s := newPutTools(memStore{waitsState: &memKV{values: map[string][]byte{}}, buckets.DeliveryWaitsState: &memKV{values: map[string][]byte{}}, buckets.DeliveredAgainState: &memKV{values: map[string][]byte{}}}, func(key string, body any) (json.RawMessage, error) {
acts = append(acts, key)
return json.RawMessage(`{"ok":true,"log":"logged"}`), nil
})
w := acting.Wait{Step: "compose", Node: "ace", Module: "nats", Part: "mesh-host", PartNode: "ace", Fp: "src2:new", Entry: "src2:a", Since: time.Now(), ClockFrom: time.Now(), Bound: "30m0s"}
raw, _ := acting.Encode(w)
s.st.put(waitsState, acting.Key("ace", "nats", "mesh-host"), raw)
got, err := s.doWaits(map[string]any{"module": "nats"})
if list := got.(map[string]any)["waits"].([]any); err != nil || len(list) != 1 || list[0].(actingSaid).BoundEnds == "" {
t.Fatalf("assigner_waits = %+v %v", got, err)
}
if _, err := s.doRelease(map[string]any{"node": "ace", "module": "nats", "how": "now"}, "x"); err == nil {
t.Error("a release with no why is taken")
}
if _, err := s.doRelease(map[string]any{"node": "ace", "module": "nats", "how": "now", "why": "the new engine is known good"}, "shanks.node-tools"); err != nil || len(acts) == 0 {
t.Fatalf("%v %v", err, acts)
}
raw, _, _, _ = s.st.get(waitsState, acting.Key("ace", "nats", "mesh-host"))
if r, _ := acting.Decode(raw); !r.Released || !strings.Contains(r.By, "known good") {
t.Errorf("wait = %+v", r)
}
}
// Design 47 G §268, A-323, A-330: the assigner and the node-engine on a node are one step: the node-engine's own want waits for no
// acting part, so it moves first, and the node's other wants, the assigner's own included, wait for the new node-engine; a want held
// on a cycle no rule breaks is the finding acting-cycle (scope module, id <node>.<module>) naming each edge's step, cleared by the
// next pass that finds it on none.
func TestTheNodeEngineIsWantedFirstAndAWantHeldOnACycleIsAFinding(t *testing.T) {
p := newPasser(kvSet{buckets.Waits(): &memKV{values: map[string][]byte{}}}, time.Date(2026, 11, 13, 2, 0, 0, 0, time.UTC))
p.publishWants = func(string, any, string) error { return nil }
findings := map[string]mcseat.Finding{}
p.findings = assign.Findings{
Put: func(f mcseat.Finding) error { findings[f.Scope+"."+f.ID+"."+f.Kind] = f; return nil },
Delete: func(key string) error { delete(findings, key); return nil },
Keys: func() ([]string, error) {
var keys []string
for k := range findings {
keys = append(keys, k)
}
return keys, nil
}}
compose := meshwants.Edge{Kind: "acting", Node: "ace", Module: "mesh-host", Fp: "src2:engine", Seat: "node-engine", Step: "compose"}
place := meshwants.Edge{Kind: "acting", Node: "ace", Module: "assigner", Fp: "src2:assigner", Seat: "mesh-wants", Step: "place"}
entries := map[string]meshwants.AssignmentEntry{
"d1": {Node: "ace", Module: "mesh-host", Fp: "src2:engine", Edges: []meshwants.Edge{place}},
"d2": {Node: "ace", Module: "assigner", Fp: "src2:assigner", Edges: []meshwants.Edge{compose}},
"d3": {Node: "ace", Module: "app", Fp: "src2:app", Edges: []meshwants.Edge{compose, place}},
}
p.graph = &graphKeeper{}
for d, e := range entries {
p.graph.computed.Revision.Entries = append(p.graph.computed.Revision.Entries, meshwants.NodeEntryRef{Node: e.Node, Module: e.Module, Digest: d})
}
p.graph.computed.Entries = entries
n := assign.Nodes{Online: map[string]bool{"ace": true}, Running: map[string]map[string]nodeengine.Running{"ace": {
"mesh-host": {Fingerprint: "src2:old"}, "assigner": {Fingerprint: "src2:old"}}}, Serves: func(nodeengine.Running, string) (bool, bool) { return false, true }}
wanted := map[string]map[string]mwc.Want{}
if got := p.actingOf("mesh-host", nil)("ace"); len(got) != 0 {
t.Errorf("the node-engine's want is held by %+v, want by no acting edge", got)
}
if got := p.actingOf("assigner", nil)("ace"); len(got) != 1 || got[0].Part != "mesh-host" {
t.Errorf("the assigner's own want is held by %+v, want by the new node-engine", got)
}
p.actingWaits(context.Background(), n, wanted)
kept := p.w.read(buckets.Waits())
if kept[acting.Key("ace", "mesh-host", "assigner")] != nil || kept[acting.Key("ace", "assigner", "mesh-host")] == nil || kept[acting.Key("ace", "app", "mesh-host")] == nil {
t.Errorf("the waits kept: %v", kept)
}
if len(findings) != 0 {
t.Errorf("the cycle the node-engine's want breaks is a finding: %v", findings)
}
// Two parts holding each other across compose and place, neither the node-engine: no rule breaks it.
entries["d4"] = meshwants.AssignmentEntry{Node: "ace", Module: "x", Fp: "src2:x", Edges: []meshwants.Edge{{Kind: "acting", Node: "ace", Module: "y", Fp: "src2:y", Seat: "s-y", Step: "place"}}}
entries["d5"] = meshwants.AssignmentEntry{Node: "ace", Module: "y", Fp: "src2:y", Edges: []meshwants.Edge{{Kind: "acting", Node: "ace", Module: "x", Fp: "src2:x", Seat: "s-x", Step: "compose"}}}
p.graph.computed.Revision.Entries = append(p.graph.computed.Revision.Entries, meshwants.NodeEntryRef{Node: "ace", Module: "x", Digest: "d4"},
meshwants.NodeEntryRef{Node: "ace", Module: "y", Digest: "d5"})
p.actingWaits(context.Background(), n, wanted)
f, ok := findings["module.ace.x.acting-cycle"]
if len(findings) != 2 || !ok || !strings.Contains(f.Summary, "ace/x -[place]-> ace/y -[compose]-> ace/x") {
t.Fatalf("the findings of a cycle no rule breaks: %v", findings)
}
// x's new version runs: y no longer waits, so neither is held on a cycle, and both findings clear.
n.Running["ace"]["x"] = nodeengine.Running{Fingerprint: "src2:x"}
p.actingWaits(context.Background(), n, wanted)
if len(findings) != 0 {
t.Errorf("the findings after the cycle broke: %v", findings)
}
}
@@ -193,20 +193,6 @@ func hearBuilds(ctx context.Context, js jetstream.JetStream, ends *builtEnds, wa
}()
}
// hearTaken registers the hub's taker of the indexer's take-in.taken, each waking the pass (orderwaits.go, §298, A-260); before
// the hub starts.
func hearTaken(hub *process.EventHub, taken *takenSources, wake func(), logf func(string, ...any)) error {
return hub.Handle(takenSubject, func(m jetstream.Msg) {
if err := taken.put(m.Data()); err != nil {
logf("%s is not kept: %v", m.Subject(), err)
}
if err := m.Ack(); err != nil {
logf("acknowledging %s: %v", m.Subject(), err)
}
wake()
})
}
// compareVersion orders two MAJOR.MINOR.PATCH versions by their numbers; a part that is no number counts as 0.
func compareVersion(a, b string) int {
pa, pb := strings.Split(a, "."), strings.Split(b, ".")
@@ -56,10 +56,10 @@ func TestAVersionReleasedHeardNamesItsVersionAndPartsBySource(t *testing.T) {
}
}
// Design 47 G §379, A-96, A-419: the trunk's entry takes its version and parts from the version-released of the source its
// fingerprint was built at (its fp-src), whatever source the kept assignment graph revision is at; a kept build from its end; no
// revision kept, another fingerprint, an fp-src with no release or none names none, and an unheard release is said once.
func TestATrunkEntryTakesItsVersionFromTheReleaseOfItsFingerprintsSource(t *testing.T) {
// Design 47 G §379, A-96, A-421; H §764, H-A-48: the trunk's entry, which the catalog stamps with no source, takes its version and
// parts from the version-released whose parts are what its build.ended made; a kept build from its end; no revision kept, another
// fingerprint and a build whose parts no release names name none, and an unheard release is said once.
func TestATrunkEntryTakesItsVersionFromTheReleaseOfItsBuildsParts(t *testing.T) {
w := newWorld()
raw, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "mail", Source: 7, Version: "1.2.3", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "mail:image", Digest: "sha256:9"}}})
if err := w.released.put(raw); err != nil {
@@ -71,10 +71,11 @@ func TestATrunkEntryTakesItsVersionFromTheReleaseOfItsFingerprintsSource(t *test
}
var logs []string
p := &passer{w: w, graph: &graphKeeper{ok: true, source: 7}, logf: func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }}
named := p.namedBuild("mail", "t", 7)
if k, ok := named("t"); !ok || k.Version != "1.2.3" || k.Parts["mail:image"] != "sha256:9" || k.KeptOn != "" {
t.Errorf("trunk entry = %+v, %v", k, ok)
named := p.namedBuild("mail", "t")
if _, ok := named("t"); ok {
t.Error("a trunk entry whose build.ended is not heard names a version")
}
_, _ = named("t")
if k, ok := named("k"); !ok || k.KeptOn != "g14" || k.Version != "" {
t.Errorf("kept build = %+v, %v", k, ok)
}
@@ -89,66 +90,23 @@ func TestATrunkEntryTakesItsVersionFromTheReleaseOfItsFingerprintsSource(t *test
if k, ok := named("old"); !ok || k.Version != "1.2.3" {
t.Errorf("a held build whose parts were released = %+v, %v; want 1.2.3", k, ok)
}
p.graph.source = 8 // a later merge that did not rebuild mail
if k, ok := named("t"); !ok || k.Version != "1.2.3" {
t.Errorf("after a later merge the trunk entry = %+v, %v; want the release of its fingerprint's source", k, ok)
// The entry's module value carries no source stamp: the catalog writes none (H-A-48).
if v, _, _ := fromEntry(meshcatalog.CatalogEntry{Module: "mail", Fp: "t", Inputs: &meshcatalog.EntryInputs{}}); v.Fp2 != "t" {
t.Errorf("the entry's module value is %+v", v)
}
if _, ok := p.namedBuild("mail", "t", 8)("t"); ok {
t.Error("an fp-src with no release names a version")
}
_, _ = p.namedBuild("mail", "t", 8)("t")
if _, ok := p.namedBuild("mail", "t", 0)("t"); ok {
t.Error("an entry naming no fp-src, whose build.ended is not heard, names a version")
}
// The release names each artifact by its whole reference, as the catalog says it, and the parts are keyed so (A-96); the
// assigner reads the entry's fp-src from its inputs (A-419).
// A-429: a released version's build counts as done for rule 1; a kept build (no version) and an unknown one do not.
if !releasedBuild(p.namedBuild("mail", "t", 7), "t") || releasedBuild(p.namedBuild("mail", "t", 7), "k") || releasedBuild(p.namedBuild("mail", "t", 8), "t") || releasedBuild(nil, "t") {
t.Error("rule 1's released build: the release of the entry's fingerprint counts, a kept build, another source or none does not")
}
if v, _, _ := fromEntry(meshcatalog.CatalogEntry{Module: "mail", Fp: "t", Inputs: &meshcatalog.EntryInputs{Src: 9, FpSrc: 7}}); v.FpSrc != 7 || v.Src != 9 {
t.Errorf("the entry's module value carries fp-src %d and src %d, want 7 and 9", v.FpSrc, v.Src)
}
// A-421: an entry naming no fp-src takes the release whose parts are what its build.ended made.
made, _ := json.Marshal(builds.BuildEnded{Module: "mail", Fingerprint: "t", Made: map[string]string{"image": "sha256:9"}})
if err := w.ends.put(made); err != nil {
t.Fatal(err)
}
if k, ok := p.namedBuild("mail", "t", 0)("t"); !ok || k.Version != "1.2.3" {
t.Errorf("an entry naming no fp-src, its build made the released digests: %+v, %v", k, ok)
p.graph.source = 8 // a later merge that did not rebuild mail
if k, ok := named("t"); !ok || k.Version != "1.2.3" || k.Parts["mail:image"] != "sha256:9" {
t.Errorf("the trunk entry whose build made the released digests: %+v, %v", k, ok)
}
// A release from an earlier source than the entry's fp-src (novox 2026-11-16, 962 against 963) is still this build's when
// its parts are exactly what the build made.
if k, ok := p.namedBuild("mail", "t", 8)("t"); !ok || k.Version != "1.2.3" || k.Parts["mail:image"] != "sha256:9" {
t.Errorf("an fp-src with no release, its build made the released digests: %+v, %v", k, ok)
}
if len(logs) != 2 || !strings.Contains(logs[0], "the release of mail at fingerprint t is not heard: no version-released of it from source 8") || !strings.Contains(logs[1], "names no fp-src, and no version-released of it names the parts its build.ended made") {
t.Errorf("logs = %q, want each unheard release said once, naming the module, the fingerprint and the source", logs)
if len(logs) != 1 || !strings.Contains(logs[0], "the release of mail at fingerprint t is not heard: no version-released of it names the parts its build.ended made") {
t.Errorf("logs = %q, want the unheard release said once, naming the module and the fingerprint", logs)
}
p.graph.ok = false
if _, ok := p.namedBuild("mail", "t", 7)("t"); ok {
if _, ok := p.namedBuild("mail", "t")("t"); ok {
t.Error("no revision kept names a release")
}
}
// A-162: the assigner knows a failed build from its `build.ended`: the error whole; a done end or none heard is not failed.
func TestTheStandingOfABuildIsHeardFromItsEnd(t *testing.T) {
w := newWorld()
say := func(e builds.BuildEnded) {
raw, _ := json.Marshal(e)
if err := w.ends.put(raw); err != nil {
t.Fatal(err)
}
}
if failed, _ := w.buildStanding("web", "fp1"); failed {
t.Error("a build nothing was heard of failed")
}
say(builds.BuildEnded{Module: "web", Fingerprint: "fp1", Outcome: builds.BuildFailed, Error: "transport fault: connection"})
if failed, why := w.buildStanding("web", "fp1"); !failed || why != "transport fault: connection" {
t.Errorf("failed end: failed %v why %q", failed, why)
}
say(builds.BuildEnded{Module: "web", Fingerprint: "fp1", Outcome: builds.BuildDone})
if failed, _ := w.buildStanding("web", "fp1"); failed {
t.Error("a later done end leaves the build failed")
}
}
@@ -34,7 +34,7 @@ func (p *passer) addedOf(node string, laid *mma.Assignments, current map[string]
p.skippedAdd(node, module, "", "the branch "+branch+" names no fingerprint of it")
continue
}
k, ok := p.namedBuild(module, fp, entry.FpSrc)(fp)
k, ok := p.namedBuild(module, fp)(fp)
if !ok {
p.skippedAdd(node, module, fp, "no version-released of it is heard for that fingerprint, so the candidate carries no version and no parts")
continue
@@ -17,19 +17,23 @@ import (
func TestACandidateThatAddsAModuleCarriesItsParts(t *testing.T) {
w := newWorld()
for _, m := range []string{"mail", "web", "db"} {
w.putModule("main", m, meshcatalog.ModulesByModuleValue{Fp2: "fp-" + m, FpSrc: 7}, graph.Node{}, nil)
w.putModule("main", m, meshcatalog.ModulesByModuleValue{Fp2: "fp-" + m}, graph.Node{}, nil)
}
w.first = "main"
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "mail", Source: 7, Version: "1.2.3", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "mail:image", Digest: "sha256:9"}}})
if err := w.released.put(rel); err != nil {
t.Fatal(err)
}
built, _ := json.Marshal(builds.BuildEnded{Module: "mail", Fingerprint: "fp-mail", Made: map[string]string{"image": "sha256:9"}})
if err := w.ends.put(built); err != nil {
t.Fatal(err)
}
end, _ := json.Marshal(builds.BuildEnded{Module: "db", Fingerprint: "fp-db", Made: map[string]string{"program": "sha256:3"}, KeptOn: "g14"})
if err := w.ends.put(end); err != nil {
t.Fatal(err)
}
w.put(buckets.Wants(), "want.ace.web", []byte(`{}`))
p := &passer{w: w, graph: &graphKeeper{ok: true, source: 9}} // a later merge: the release is matched by fp-src (A-419)
p := &passer{w: w, graph: &graphKeeper{ok: true, source: 9}} // a later merge: the release is matched by the parts its build made (A-421, H-A-48)
laid := &mma.Assignments{Node: "ace", Modules: []mma.PlacedModule{{Module: "mail"}, {Module: "web"}, {Module: "db"}, {Module: "old"}}}
current := map[string]mma.Assignments{"ace": {Node: "ace", Modules: []mma.PlacedModule{{Module: "old"}}}}
c := p.candidateOf("p1", "ace", laid, current)
@@ -370,6 +370,11 @@ func (c *compositionSteps) takeUp(ctx context.Context, r *compositionRuns) {
if reader.Ended != nil {
again = reader.ask
}
go c.say1(ctx, reader.ID, stepRunOf(reader.CompositionReader), c.resume, again)
how := c.howOf(reader.Step, true)
if how == nil {
c.logf("the step %s of %s is not taken up again: it is no composition or validate step (%q)", reader.ID, reader.Module, reader.Step)
continue
}
go c.say1(ctx, reader.ID, stepRunOf(reader.CompositionReader), how, again)
}
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
"sync"
@@ -12,6 +13,8 @@ import (
"github.com/nats-io/nats.go/jetstream"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
@@ -19,12 +22,13 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
"git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-assigner/internal/assign"
)
// The run of a composition step (design 47 G §354, §63, §64, §718; A-226, A-238, A-240, A-252, A-254, A-261): the step reads one
// composition run per machine of its candidate (compositionruns.go), and the step that starts a machine's run composes it: one
// compose-candidate ask of the node, one composer.Request, depth compose, the one machine and one case `change`, its manifests,
// verdicts and seats from the step's catalog revision read through mesh-catalog's `revision`, kept once in `inputs`; one run ask
// compose-candidate ask of the node, one composer.Request, depth compose, the one machine and one case `change`, its manifests
// and seats from the step's catalog revision read through mesh-catalog's `revision`, kept once in `inputs`; one run ask
// of the seat node-build-go, naming no head, its program the node-engine build's catalog entry with the composer's package,
// chosen once and recorded in the run. The run's end is heard on the build seat's step-ended of that ask, its answer (a
// composer.Verdict) read from `output`, and written in the run's key, whose change every reading step hears. A machine the
@@ -53,6 +57,18 @@ type compositionRun struct {
call func(key string, body any) (json.RawMessage, error)
// trunk is the trunk's catalog half as the assigner holds it.
trunk func() (mcc.Half, bool)
// newest is the newest catalog half the assigner's views hold of each watched branch (halves.views), and watched a module's
// watched branches in its registration's order (halves.watchedOf): a machine's composition takes each module's manifest across
// them (design 47 H-A-143, G §532). Nil: the step's revision alone.
newest func() map[string]mcc.Half
watched func(module string) []string
// assigned is the modules the assignments place on a machine (world.assignments), for the modules no watched branch lists;
// assignment is the machine's assignments whole, which the case composes with those modules left out (H-A-148).
assigned func(node string) []string
assignment func(node string) (mma.Assignments, bool)
// findings is where the step raises the finding assignment-unlisted of each assignment it leaves out (H-A-149); the pass over
// the assignments clears it.
findings assign.Findings
// running is the last `running` heard of a module on a node (world.runningOf), never the node-engine's bucket.
running func(node, module string) (ne.Running, bool)
// away says the watchman holds machine away (machine-away, not back since): the one presence the assigner keeps (world.awayNow),
@@ -188,7 +204,8 @@ func couldNotRun(said string) stepOutcome {
}
// runPrep is what the step that starts a run reads of its catalog revision, once for every machine it starts: the seats, the
// case's manifests and verdicts, and the composer program per machine.
// case's manifests, and the composer program per machine. The case carries no verdicts: the step validate judged the
// manifests before the composition step (design 47 H-A-112, H-A-108).
type runPrep struct {
r *compositionRun
step meshwants.StepRun
@@ -196,7 +213,6 @@ type runPrep struct {
// read once
seats []json.RawMessage
manifests map[string]composer.Manifest
verdicts map[string]json.RawMessage
none map[string]string
programOf func(node string) (buildstep.RunProgram, string, error)
err error
@@ -209,10 +225,13 @@ func (p *runPrep) get(ctx context.Context) error {
p.err = errors.New("the step's catalog revision is not read: " + err.Error())
return
}
if p.r.newest != nil && p.r.watched != nil {
half = acrossBranches(p.step, half, p.r.newest(), p.r.watched)
}
if p.seats, p.err = p.r.seats(ctx, half.Revision.Definitions); p.err != nil {
return
}
if p.manifests, p.verdicts, p.none, p.err = caseOf(half); p.err != nil {
if p.manifests, p.none, p.err = caseOf(half); p.err != nil {
return
}
p.programOf, p.err = p.r.programs(ctx, half)
@@ -229,6 +248,21 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
r.logf("the composition run %s is not ended: %v", key, err)
}
}
// The one set of unlisted assignments, read once at the run's start and carried on the run to the leaving-out, the finding and
// every step's judgement, the resume's too (design 47 H-A-152, H-A-153).
unlisted := r.unlistedOn(node)
if len(unlisted) > 0 {
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
if c.Ask != ask || c.Ended != nil {
return false
}
c.Unlisted = unlisted
return true
}); err != nil {
end(node + ": the run's unlisted assignments are not written: " + err.Error())
return
}
}
if err := prep.get(ctx); err != nil {
end(node + ": " + err.Error())
return
@@ -243,8 +277,15 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
end(node + ": " + err.Error())
return
}
cs := composer.Case{Name: changeCase, Manifests: prep.manifests, None: prep.none}
if left, err := r.leftOut(node, unlisted); err != nil {
end(node + ": " + err.Error())
return
} else if left != nil {
cs.Assignments = left
}
req := composer.Request{V: composer.Version, Input: in.Body, Depth: composer.DepthCompose, Machines: []string{node},
Cases: []composer.Case{{Name: changeCase, Manifests: prep.manifests, Verdicts: prep.verdicts, None: prep.none}}, Seats: prep.seats,
Cases: []composer.Case{cs}, Seats: prep.seats,
BlameTries: r.runs.set.blameTries} // the composer's bound of its search for culprits (§721, A-466r)
raw, err := json.Marshal(req)
if err != nil {
@@ -289,7 +330,29 @@ const notTried = "not tried: the search reached its bound"
// could not run where the module was not tried (A-470b); a machine that does not compose and blames no module fails every step on
// it, on the node's own account; a verdict with no `blamed` (a composer before §721) is judged as before, with the warning "the
// composer names no culprits"; otherwise the machine passes, with a warning for each other module blamed there.
//
// The run's unlisted are the modules the machine is assigned that no watched branch's newest revision lists, left out of its
// composition, as the run's start read them (H-A-152, H-A-153): each is said on every path, in the machine's failed or
// could-not-run words where one is set, else as a warning, never the machine's failure and never dropped in silence (H-A-143,
// H-A-144, H-A-148).
func judgeRun(module string, run meshwants.CompositionRun) machineEnd {
end := judgeVerdict(module, run)
for _, u := range run.Unlisted {
said := run.Machine + " is assigned " + u + ", which no watched branch lists (H-A-143)"
switch {
case end.failed != "":
end.failed += "; " + said
case end.couldNot != "":
end.couldNot += "; " + said
default:
end.warnings = append(end.warnings, said)
}
}
return end
}
// judgeVerdict is judgeRun before the unlisted modules are said.
func judgeVerdict(module string, run meshwants.CompositionRun) machineEnd {
node := run.Machine
if run.Ended == nil {
return machineEnd{couldNot: node + ": the step stopped before its composition run " + runKeyOf(run.Candidate, node) + " ended"}
@@ -479,12 +542,10 @@ func (r *compositionRun) seatAt(ctx context.Context, seat, digest string) (json.
return def, nil
}
// caseOf is the case's manifests, verdicts and none from the revision's entries: each manifest whole, the verdict of each one not
// accepted (a module without one is accepted), and the revision's none words of each module it gives no fingerprint, whose
// build can never be made (design 47 G A-470j, A-470k).
func caseOf(half mcc.Half) (map[string]composer.Manifest, map[string]json.RawMessage, map[string]string, error) {
// caseOf is the case's manifests and none from the revision's entries: each manifest whole, and the revision's none words of each
// module it gives no fingerprint, whose build can never be made (design 47 G A-470j, A-470k). It sets no verdicts (H-A-112).
func caseOf(half mcc.Half) (map[string]composer.Manifest, map[string]string, error) {
manifests := map[string]composer.Manifest{}
verdicts := map[string]json.RawMessage{}
var none map[string]string
for name, e := range half.Entries {
if len(e.Manifest) == 0 {
@@ -492,7 +553,7 @@ func caseOf(half mcc.Half) (map[string]composer.Manifest, map[string]json.RawMes
}
raw, err := json.Marshal(e.Manifest)
if err != nil {
return nil, nil, nil, fmt.Errorf("the manifest of %s cannot be encoded: %w", name, err)
return nil, nil, fmt.Errorf("the manifest of %s cannot be encoded: %w", name, err)
}
manifests[name] = composer.Manifest{Raw: raw}
if e.Fp == "" && e.None != "" {
@@ -501,23 +562,137 @@ func caseOf(half mcc.Half) (map[string]composer.Manifest, map[string]json.RawMes
}
none[name] = e.None
}
if e.Verdict == "" || e.Verdict == mcc.VerdictAccepted {
continue
}
v := meshcatalog.VerdictsByDigestValue{V: 1, Module: name, State: e.Verdict}
if e.Verdict != mcc.VerdictRefused {
v.State = mcc.VerdictManifestWaits
}
if e.Inputs != nil {
v.Problems, v.Unknown, v.Warnings = e.Inputs.Problems, e.Inputs.Unknown, e.Inputs.Warnings
}
raw, err = json.Marshal(v)
if err != nil {
return nil, nil, nil, err
}
verdicts[name] = raw
}
return manifests, verdicts, none, nil
return manifests, none, nil
}
// acrossBranches is the catalog half a machine's composition reads (design 47 H-A-143, H-A-144, G §532): each module's entry from
// the newest revision of the first of its watched branches, in its registration's order, that lists it, none for a module with no
// watched branches; the candidate's revision replaces its
// branch's newest for the modules it moves (its movers and the step's module), and the whole of it where it is that branch's newest
// or the branch's is not held. The half keeps the candidate's revision, its definitions with it.
func acrossBranches(step meshwants.StepRun, candidate mcc.Half, newest map[string]mcc.Half, watched func(module string) []string) mcc.Half {
halves := make(map[string]mcc.Half, len(newest)+1)
for b, h := range newest {
halves[b] = h
}
if own, held := newest[step.Branch]; !held || candidate.Revision.Revision >= own.Revision.Revision {
halves[step.Branch] = candidate
} else {
mix := mcc.Half{Revision: own.Revision, Entries: maps.Clone(own.Entries)}
moved := []string{step.Module}
for _, m := range candidate.Revision.Movers {
moved = append(moved, m.Module)
}
for _, m := range moved {
if e, ok := candidate.Entries[m]; ok {
mix.Entries[m] = e
} else {
delete(mix.Entries, m)
}
}
halves[step.Branch] = mix
}
out := mcc.Half{Revision: candidate.Revision, Entries: map[string]meshcatalog.CatalogEntry{}}
for _, h := range halves {
for name := range h.Entries {
if _, done := out.Entries[name]; done {
continue
}
for _, b := range watched(name) { // none: no watched branch lists it, it is unlisted (H-A-144)
if e, ok := halves[b].Entries[name]; ok {
out.Entries[name] = e
break
}
}
}
}
return out
}
// unlistedOn is the one set of unlisted assignments of node (H-A-152): the modules the assignments place there that the newest
// revision of none of their watched branches lists, a module with no watched branches among them (H-A-143, H-A-144), by name.
// The candidate never enters it, so a module the change drops while still assigned stays in the composition and fails it as the
// change's own fault (ADR 0578 §2). Where the newest revisions are not followed yet nothing is unlisted: none while no branch's
// newest is held, and not a module one of whose watched branches' newest is not held yet.
func (r *compositionRun) unlistedOn(node string) []string {
if r.assigned == nil || r.newest == nil || r.watched == nil {
return nil
}
newest := r.newest()
if len(newest) == 0 {
return nil
}
var out []string
for _, m := range r.assigned(node) {
watched := r.watched(m)
if !listedOn(newest, watched, m) && !slices.ContainsFunc(watched, func(b string) bool { _, held := newest[b]; return !held }) {
out = append(out, m)
}
}
slices.Sort(out)
return slices.Compact(out)
}
// leftOut is the case's assignments of node with each module of the run's unlisted set left out, or nil where none is (the case
// then composes the input's): a stale assignment is a fault of the assignments, not of the change judged, so it is left out of the
// composition, said in the journal, raised as assignment-unlisted and, at the judgement, said as unlisted from the same set
// (design 47 H-A-148, H-A-149, H-A-152, H-A-143; ADR 0578 §2).
func (r *compositionRun) leftOut(node string, set []string) (map[string]json.RawMessage, error) {
if r.assignment == nil || len(set) == 0 {
return nil, nil
}
a, ok := r.assignment(node)
if !ok {
return nil, nil
}
var unlisted []string
for _, m := range a.Modules {
if slices.Contains(set, m.Module) {
unlisted = append(unlisted, m.Module)
}
}
if len(unlisted) == 0 {
return nil, nil
}
a.Modules = slices.DeleteFunc(slices.Clone(a.Modules), func(m mma.PlacedModule) bool { return slices.Contains(unlisted, m.Module) })
raw, err := mmac.EncodeAssignments(a)
if err != nil {
return nil, fmt.Errorf("its assignments with %s left out cannot be encoded: %w", strings.Join(unlisted, ", "), err)
}
r.logf("%s: the composition leaves out %s, assigned there and listed on no watched branch (H-A-148)", node, strings.Join(unlisted, ", "))
for _, m := range unlisted {
r.raiseUnlisted(node, m)
}
return map[string]json.RawMessage{node: raw}, nil
}
// raiseUnlisted writes the finding assignment-unlisted of module on node (H-A-149); one not written is said in the journal.
func (r *compositionRun) raiseUnlisted(node, module string) {
if r.findings.Put == nil {
return
}
now := r.now
if now == nil {
now = time.Now
}
f, err := assign.UnlistedFinding(node, module, now())
if err == nil {
err = r.findings.Put(f)
}
if err != nil {
r.logf("the finding %s is not written: %v", assign.UnlistedKey(node, module), err)
}
}
// listedOn says whether the newest revision of one of module's watched branches lists it (H-A-143, H-A-144).
func listedOn(newest map[string]mcc.Half, watched []string, module string) bool {
for _, b := range watched {
if _, ok := newest[b].Entries[module]; ok {
return true
}
}
return false
}
// nodeEngineEntry is the entry of the module that claims the seat node-engine, or false.
@@ -633,3 +808,32 @@ func runAskPublisher(js jetstream.JetStream) func(ctx context.Context, a buildst
return err
}
}
// newestOf is the newest catalog half the views hold of each watched branch, or nil while the catalog half is not followed.
func (iv *catalogViews) newestOf() func() map[string]mcc.Half {
if iv == nil {
return nil
}
return func() map[string]mcc.Half {
if iv.h == nil {
return map[string]mcc.Half{}
}
return iv.h.views()
}
}
// listed says whether one of module's watched branches lists it in the newest revision the views hold (H-A-149's clear).
func (iv *catalogViews) listed(module string) bool {
if iv == nil || iv.h == nil {
return false
}
return listedOn(iv.h.views(), iv.h.watchedOf(module), module)
}
// watchedOf is a module's watched branches in its registration's order (halves.watchedOf); none while the half is not followed.
func (iv *catalogViews) watchedOf(module string) []string {
if iv == nil || iv.h == nil {
return nil
}
return iv.h.watchedOf(module)
}
@@ -4,18 +4,24 @@ import (
"context"
"encoding/json"
"errors"
"maps"
"slices"
"strings"
"sync"
"testing"
"time"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
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"
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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
"git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-assigner/internal/assign"
)
const (
@@ -157,7 +163,7 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
}
// Design 47 G §354, §63, §64, A-226, A-238, A-240, A-243, A-252, A-254, A-261: one request and one run ask per machine, the request
// depth compose with the one machine and one case `change`, its manifests, verdicts and seats from the step's revision; the
// depth compose with the one machine and one case `change`, its manifests and seats from the step's revision, no verdicts (H-A-112); the
// composer is the node-engine build each machine runs, its entry read through `entry`, or the revision's where it differs from the
// trunk's, or the revision's for a machine whose node-engine is not heard running (A-451); the run's verdict is read from its step-ended; a machine away passes with a warning, one not composing fails the step.
func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
@@ -185,9 +191,8 @@ func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
t.Errorf("the request of ace %+v", req)
}
c := req.Cases[0]
if string(c.Manifests["m"].Raw) != `{"module":"m"}` || len(c.Manifests) != 4 || len(c.None) != 1 || c.None["lidarr"] != "builders disagree: node" || len(c.Verdicts) != 1 || !strings.Contains(string(c.Verdicts["bad"]), `"refused"`) ||
!strings.Contains(string(c.Verdicts["bad"]), "no seat x") {
t.Errorf("the case %+v %s", c.Manifests, c.Verdicts)
if string(c.Manifests["m"].Raw) != `{"module":"m"}` || len(c.Manifests) != 4 || len(c.None) != 1 || c.None["lidarr"] != "builders disagree: node" {
t.Errorf("the case %+v", c.Manifests)
}
if strings.Join(s.entries, " ") == "" {
t.Error("no node-engine entry is read through entry")
@@ -260,6 +265,104 @@ func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
}
}
// Another watched branch's app is in every machine's case, and a module assigned there that no watched branch lists is said in
// the machine's reason (H-A-143, §532).
across := newRunStand(t, "src2:e1", "src2:e1", "d1")
across.r.newest = func() map[string]mcc.Half {
return map[string]mcc.Half{"master": {Revision: meshcatalog.CatalogRevision{Branch: "master", Revision: 2},
Entries: map[string]meshcatalog.CatalogEntry{"f1-circuits": {Module: "f1-circuits", Fp: "f1", Manifest: map[string]any{"module": "f1-circuits"}}}}}
}
across.r.watched = func(module string) []string {
if module == "checker" || module == "lidarr" { // no registration names them; lidarr is on main's revision all the same (H-A-144)
return nil
}
return []string{"main", "master"}
}
across.r.assigned = func(node string) []string { return []string{"m", "f1-circuits", "checker", "lidarr"} }
if out := across.r.run(context.Background(), "ask-step", step); out.Outcome != meshwants.StepEndedOutcomeFailed ||
!strings.Contains(out.Said, "g14 is assigned checker, which no watched branch lists (H-A-143)") ||
!strings.Contains(out.Said, "g14 is assigned lidarr, which no watched branch lists (H-A-143)") {
t.Errorf("the step across the watched branches came to %+v", out)
}
if c := across.requests["ace"].Cases[0]; string(c.Manifests["f1-circuits"].Raw) != `{"module":"f1-circuits"}` || len(c.Manifests) != 4 ||
c.Manifests["lidarr"].Raw != nil {
t.Errorf("the case across the watched branches holds %v", slices.Sorted(maps.Keys(c.Manifests)))
}
if c := across.requests["ace"].Cases[0]; c.Assignments != nil {
t.Errorf("with no assignments held the case composes the input's, it carries %v", c.Assignments)
}
// A stale assignment is left out of the case's assignments as well, said, and the machine composes; a listed module stays in
// (H-A-148, ADR 0578 §2). The one set is the watched branches' newest revisions', carried on the run (H-A-152, H-A-153): a module
// the candidate drops while the newest still lists it stays in, the change's own fault, and while no newest revision is followed
// nothing is left out.
dropsWeb := func() map[string]mcc.Half {
h := across.r.newest()
h["main"] = mcc.Half{Revision: meshcatalog.CatalogRevision{Branch: "main", Revision: 6},
Entries: map[string]meshcatalog.CatalogEntry{"m": {Module: "m", Manifest: map[string]any{"module": "m"}},
"web": {Module: "web", Fp: "w1", Manifest: map[string]any{"module": "web"}}}}
return h
}
for _, tc := range []struct {
name string
assigned []string
newest func() map[string]mcc.Half // nil: across's
want []string // the case's modules of ace; nil: the input's assignments
}{
{"a stale assignment left out and said, the machine composes", []string{"m", "f1-circuits", "checker"}, nil, []string{"m", "f1-circuits"}},
{"listed modules alone: the input's assignments", []string{"m", "f1-circuits"}, nil, nil},
{"a module the candidate drops, the newest lists: kept", []string{"m", "f1-circuits", "web"}, dropsWeb, nil},
{"no newest revision followed: nothing left out", []string{"m", "checker"}, func() map[string]mcc.Half { return map[string]mcc.Half{} }, nil},
} {
left := newRunStand(t, "src2:e1", "src2:e1", "d1")
left.r.newest, left.r.watched = across.r.newest, across.r.watched
if tc.newest != nil {
left.r.newest = tc.newest
}
left.r.assigned = func(string) []string { return tc.assigned }
left.r.assignment = func(node string) (mma.Assignments, bool) {
a := mma.Assignments{Node: node}
for _, m := range tc.assigned {
a.Modules = append(a.Modules, mma.PlacedModule{Module: m})
}
return a, true
}
left.verdict = func(string) (composer.Machine, bool) { return composer.Machine{Composes: true}, true }
raised := map[string][]byte{}
left.r.findings = assign.Findings{Put: putInto(raised)}
out := left.r.run(context.Background(), "ask-step", step)
// H-A-149: the step that leaves an assignment out raises assignment-unlisted, scope delivery, id <node>.<module>, a warning.
var f mcseat.Finding
_ = json.Unmarshal(raised[assign.UnlistedKey("ace", "checker")], &f)
if want := tc.want != nil; want != (f.Kind == assign.KindAssignmentUnlisted && f.Scope == "delivery" && f.ID == "ace.checker" &&
f.Severity == mcseat.FindingSeverityWarning) || (!want && len(raised) != 0) {
t.Errorf("%s: raised %v", tc.name, raised)
}
said := "ace is assigned checker, which no watched branch lists (H-A-143)"
if out.Outcome != meshwants.StepEndedOutcomePassed || (tc.want != nil) != slices.Contains(out.Warnings, said) {
t.Errorf("%s: the step came to %+v", tc.name, out)
}
if run, _, _, _ := left.runs.read(runKeyOf("main.7", "ace")); (tc.want != nil) != slices.Equal(run.Unlisted, []string{"checker"}) ||
(tc.want == nil && run.Unlisted != nil) {
t.Errorf("%s: the run carries the unlisted %v", tc.name, run.Unlisted)
}
raw, ok := left.requests["ace"].Cases[0].Assignments["ace"]
if tc.want == nil {
if ok {
t.Errorf("%s: the case carries assignments %s", tc.name, raw)
}
continue
}
a, err := mmac.DecodeAssignments(raw)
var got []string
for _, m := range a.Modules {
got = append(got, m.Module)
}
if err != nil || !slices.Equal(got, tc.want) {
t.Errorf("%s: the case composes ace with %v (%v), want %v", tc.name, got, err, tc.want)
}
}
// At the inputs state's cap the ask is refused, naming the store (§354).
full := newRunStand(t, "src2:e1", "src2:e1", "d1")
full.r.keeper.used = func() (int64, error) { return inputsCap, nil }
@@ -439,21 +542,35 @@ func TestAMachineIsJudgedByTheModulesItBlames(t *testing.T) {
run meshwants.CompositionRun
failed, couldNo string
warnings []string
unlisted []string
}{
{"blamed module fails", "a", runOf(blamesA), "ace holds a: /etc/x is a's and c's", "", nil},
{"another module passes with a warning", "b", runOf(blamesA), "", "", []string{"ace holds a: /etc/x is a's and c's"}},
{"blames no module fails both", "b", runOf(`{"composes":false,"reason":"the node's own composition","blamed":[]}`), "ace does not compose and blames no module: the node's own composition", "", nil},
{"an old composer", "b", runOf(`{"composes":false,"reason":"x"}`), "ace does not compose: x", "", []string{"ace: the composer names no culprits"}},
{"composes", "b", runOf(`{"composes":true,"blamed":[]}`), "", "", nil},
{"blamed module fails", "a", runOf(blamesA), "ace holds a: /etc/x is a's and c's", "", nil, nil},
{"another module passes with a warning", "b", runOf(blamesA), "", "", []string{"ace holds a: /etc/x is a's and c's"}, nil},
{"blames no module fails both", "b", runOf(`{"composes":false,"reason":"the node's own composition","blamed":[]}`), "ace does not compose and blames no module: the node's own composition", "", nil, nil},
{"an old composer", "b", runOf(`{"composes":false,"reason":"x"}`), "ace does not compose: x", "", []string{"ace: the composer names no culprits"}, nil},
{"composes", "b", runOf(`{"composes":true,"blamed":[]}`), "", "", nil, nil},
{"own module not tried", "a", runOf(`{"composes":false,"blamed":[{"module":"a","problem":"not tried: the search reached its bound"}]}`), "",
"ace holds a untried: the composer's search for culprits reached its bound of blame_tries (A-470b)", nil},
"ace holds a untried: the composer's search for culprits reached its bound of blame_tries (A-470b)", nil, nil},
{"another not tried", "b", runOf(`{"composes":false,"blamed":[{"module":"a","problem":"not tried: the search reached its bound"}]}`), "", "",
[]string{"ace holds a: not tried: the search reached its bound"}},
{"not judged", "a", runOf(`{"composes":false,"not_judged":"no seat list","blamed":[]}`), "", "ace was not judged: no seat list", nil},
{"could not run", "a", meshwants.CompositionRun{Machine: "ace", Ended: &at, Outcome: meshwants.CompositionRunOutcomeCouldNotRun, Said: "ace: gone"}, "", "ace: gone", nil},
[]string{"ace holds a: not tried: the search reached its bound"}, nil},
{"not judged", "a", runOf(`{"composes":false,"not_judged":"no seat list","blamed":[]}`), "", "ace was not judged: no seat list", nil, nil},
{"could not run", "a", meshwants.CompositionRun{Machine: "ace", Ended: &at, Outcome: meshwants.CompositionRunOutcomeCouldNotRun, Said: "ace: gone"}, "", "ace: gone", nil, nil},
// H-A-143: a module assigned there that no watched branch lists is said in the reason, or as a warning where it composes.
{"an unlisted module in the reason", "b", runOf(`{"composes":false,"reason":"nothing provides \"photos\"","blamed":[]}`),
"ace does not compose and blames no module: nothing provides \"photos\"; ace is assigned photos, which no watched branch lists (H-A-143)", "", nil, []string{"photos"}},
{"does not compose, blames a module, an unlisted module", "a", runOf(`{"composes":false,"reason":"nothing provides \"photos\"","blamed":[{"module":"a","problem":"nothing provides \"photos\""}]}`),
"ace holds a: nothing provides \"photos\"; ace is assigned photos, which no watched branch lists (H-A-143)", "", nil, []string{"photos"}},
{"another module blamed, an unlisted module", "b", runOf(`{"composes":false,"blamed":[{"module":"a","problem":"x"}]}`), "", "",
[]string{"ace holds a: x", "ace is assigned photos, which no watched branch lists (H-A-143)"}, []string{"photos"}},
{"could not run, an unlisted module", "a", meshwants.CompositionRun{Machine: "ace", Ended: &at, Outcome: meshwants.CompositionRunOutcomeCouldNotRun, Said: "ace: gone"},
"", "ace: gone; ace is assigned photos, which no watched branch lists (H-A-143)", nil, []string{"photos"}},
{"an unlisted module where it composes", "b", runOf(`{"composes":true,"blamed":[]}`), "", "",
[]string{"ace is assigned photos, which no watched branch lists (H-A-143)"}, []string{"photos"}},
} {
t.Run(tc.name, func(t *testing.T) {
e := judgeRun(tc.module, tc.run)
run := tc.run
run.Unlisted = tc.unlisted // the set the run's start wrote (H-A-153)
e := judgeRun(tc.module, run)
if e.failed != tc.failed || e.couldNot != tc.couldNo || !slices.Equal(e.warnings, tc.warnings) {
t.Errorf("judged %+v, want failed %q, could not run %q, warnings %q", e, tc.failed, tc.couldNo, tc.warnings)
}
@@ -573,3 +690,106 @@ func TestARerunMovesEveryReaderThatDidNotPass(t *testing.T) {
}
}
}
// Design 47 H-A-143, G §532: a machine's composition takes each module's entry from the newest revision of the first of its
// watched branches, in its registration's order, that lists it; the candidate's revision replaces its branch's newest for the
// modules it moves, and whole where it is that branch's newest; the half keeps the candidate's revision.
func TestACompositionTakesEachModuleAcrossTheWatchedBranches(t *testing.T) {
entry := func(module, fp string) meshcatalog.CatalogEntry {
return meshcatalog.CatalogEntry{Module: module, Fp: fp, Manifest: map[string]any{"module": module}}
}
half := func(branch string, revision int64, movers []string, entries ...meshcatalog.CatalogEntry) mcc.Half {
h := mcc.Half{Revision: meshcatalog.CatalogRevision{Branch: branch, Revision: revision, Definitions: []meshcatalog.CatalogRevisionDefinitionsItem{{Seat: "s1", Digest: branch}}},
Entries: map[string]meshcatalog.CatalogEntry{}}
for _, m := range movers {
h.Revision.Movers = append(h.Revision.Movers, meshcatalog.TakeInEntry{Module: m})
}
for _, e := range entries {
h.Entries[e.Module] = e
}
return h
}
newest := map[string]mcc.Half{
"main": half("main", 4, nil, entry("engine", "e1"), entry("a", "a1"), entry("both", "main")),
"master": half("master", 9, nil, entry("f1-circuits", "f1")),
"nox-mesh": half("nox-mesh", 3, nil, entry("link2pay", "l1"), entry("photos", "p1"), entry("both", "nox")),
}
registrations := map[string][]string{"both": {"nox-mesh", "main"}, "f1-circuits": {"master"}, "link2pay": {"nox-mesh"}, "photos": {"nox-mesh"}}
registrations["engine"], registrations["a"] = []string{"main"}, []string{"main"}
watched := func(module string) []string { return registrations[module] } // a module no registration names has none (H-A-144)
for _, tc := range []struct {
name string
step meshwants.StepRun
candidate mcc.Half
newest map[string]mcc.Half
want map[string]string // module -> fingerprint
}{
{"the newest of main, the others' apps beside it", meshwants.StepRun{Branch: "main", Module: "a", Revision: 5},
half("main", 5, []string{"a"}, entry("engine", "e1"), entry("a", "a2"), entry("both", "main")), newest,
map[string]string{"engine": "e1", "a": "a2", "both": "nox", "f1-circuits": "f1", "link2pay": "l1", "photos": "p1"}},
{"an older candidate moves only its movers", meshwants.StepRun{Branch: "nox-mesh", Module: "link2pay", Revision: 2},
half("nox-mesh", 2, []string{"photos"}, entry("link2pay", "l0"), entry("both", "nox0")), newest,
map[string]string{"engine": "e1", "a": "a1", "both": "nox", "f1-circuits": "f1", "link2pay": "l0"}},
{"a branch not yet held is the candidate's", meshwants.StepRun{Branch: "master", Module: "f1-circuits", Revision: 1},
half("master", 1, nil, entry("f1-circuits", "f0")), map[string]mcc.Half{"main": newest["main"]},
map[string]string{"engine": "e1", "a": "a1", "both": "main", "f1-circuits": "f0"}},
{"no view held yet: the candidate alone", meshwants.StepRun{Branch: "main", Module: "a", Revision: 5},
half("main", 5, nil, entry("a", "a2")), nil, map[string]string{"a": "a2"}},
{"a module no registration names is not composed", meshwants.StepRun{Branch: "main", Module: "a", Revision: 5},
half("main", 5, nil, entry("a", "a2"), entry("checker", "c1")), nil, map[string]string{"a": "a2"}},
} {
t.Run(tc.name, func(t *testing.T) {
got := acrossBranches(tc.step, tc.candidate, tc.newest, watched)
fps := map[string]string{}
for name, e := range got.Entries {
fps[name] = e.Fp
}
if !maps.Equal(fps, tc.want) {
t.Errorf("composed from %v, want %v", fps, tc.want)
}
if got.Revision.Revision != tc.candidate.Revision.Revision || len(got.Revision.Definitions) != 1 || got.Revision.Definitions[0].Digest != tc.step.Branch {
t.Errorf("the half keeps revision %d with definitions %v, want the candidate's %d with its own", got.Revision.Revision, got.Revision.Definitions,
tc.candidate.Revision.Revision)
}
})
}
}
// Design 47 H-A-149: the pass over the assignments clears assignment-unlisted when the assignment is gone or one of the module's
// watched branches lists it again, and keeps it while it stands; another finding is left alone.
func TestThePassClearsAnUnlistedAssignmentsFinding(t *testing.T) {
for _, tc := range []struct {
name string
assigned []string // novox's modules
listed bool
kept bool
}{
{"still assigned and listed nowhere: kept", []string{"checker"}, false, true},
{"the assignment gone: cleared", []string{"web"}, false, false},
{"listed again: cleared", []string{"checker"}, true, false},
} {
t.Run(tc.name, func(t *testing.T) {
w := newWorld()
a := mma.Assignments{V: keys.Version, Node: "novox"}
for _, m := range tc.assigned {
a.Modules = append(a.Modules, mma.PlacedModule{Module: m})
}
putAssignments(w, a)
findings := map[string][]byte{}
f, _ := assign.UnlistedFinding("novox", "checker", time.Now())
_ = putInto(findings)(f)
other, _ := assign.UnplacedFinding("g14", time.Now())
_ = putInto(findings)(other)
p := &passer{w: w, logf: t.Logf, listed: func(string) bool { return tc.listed }, findings: assign.Findings{Put: putInto(findings),
Delete: func(k string) error { delete(findings, k); return nil },
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(findings)), nil }}}
p.clearUnlisted()
if _, ok := findings[assign.UnlistedKey("novox", "checker")]; ok != tc.kept {
t.Errorf("the finding kept %v, want %v", ok, tc.kept)
}
if _, ok := findings[assign.UnplacedKey("g14")]; !ok {
t.Error("another finding is cleared")
}
})
}
}
@@ -374,7 +374,11 @@ type joined struct {
// written create-only (or replacing the ended key by compare-and-set), the reader its first, ask its run ask's id. At the
// cap no run is started, an error naming the fill.
func (r *compositionRuns) join(reader meshwants.CompositionReader, candidate, machine, ask string) (joined, error) {
key := runKeyOf(candidate, machine)
return r.joinAt(runKeyOf(candidate, machine), reader, candidate, machine, ask)
}
// joinAt is join of the run under key: a machine's composition run, or a revision's validate run with no machine (H-A-108).
func (r *compositionRuns) joinAt(key string, reader meshwants.CompositionReader, candidate, machine, ask string) (joined, error) {
for {
run, rev, ok, err := r.read(key)
if err != nil {
@@ -539,12 +543,7 @@ func (r *compositionRuns) clearBounds(key, ask string, prefixes ...string) error
// stepEnded writes at as the `ended` of the reader asked under id in each run of its step's candidate naming it, by
// compare-and-set (A-470m): the time its step said its end, carried with it into a rerun's run.
func (r *compositionRuns) stepEnded(id string, step meshwants.StepRun, at time.Time) {
candidate, err := candidateKeyOf(step)
if err != nil {
r.logf("the end of the composition step %s is not written on its runs: %v", id, err)
return
}
keys, err := r.keysOf(candidate, id)
keys, err := r.keysOfStep(step, id)
if err != nil {
r.logf("the end of the composition step %s is not written on its runs: %v", id, err)
return
@@ -564,6 +563,23 @@ func (r *compositionRuns) stepEnded(id string, step meshwants.StepRun, at time.T
}
}
// keysOfStep are the keys of the runs the step asked under id reads: its revision's validate run for a validate step, its
// candidate's runs naming it for a composition step.
func (r *compositionRuns) keysOfStep(step meshwants.StepRun, id string) ([]string, error) {
if step.Step == meshwants.StepRunStepValidate {
key, err := validateKeyOf(step)
if err != nil {
return nil, err
}
return []string{key}, nil
}
candidate, err := candidateKeyOf(step)
if err != nil {
return nil, err
}
return r.keysOf(candidate, id)
}
// hasReader is whether readers holds the step asked under id.
func hasReader(readers []meshwants.CompositionReader, id string) bool {
return slices.ContainsFunc(readers, func(c meshwants.CompositionReader) bool { return c.ID == id })
@@ -672,6 +688,10 @@ func (r *compositionRuns) heardEnd(e buildstep.StepEnded, read func(buildstep.St
said = fmt.Sprintf("%s: its run ask %s ended %s on %s: %s", node, e.Ask, e.Outcome, e.Node, e.Said)
} else if answer, err := read(e); err != nil { // the program's last line of standard output (A-254)
said = node + ": " + err.Error()
} else if isValidateRun(run) {
if verdict, said = validateRunVerdict(answer); said == "" {
outcome = meshwants.CompositionRunOutcomePassed
}
} else if verdict, said = runVerdict(node, answer); said == "" {
outcome = meshwants.CompositionRunOutcomePassed
}
@@ -798,7 +818,7 @@ func (r *compositionRuns) leave(pipeline string, stop func(ids []string)) ([]str
// passedOn is whether the step of module passed on the machine of an ended run (§722): neither failed nor could not run there.
func passedOn(module string, run meshwants.CompositionRun) bool {
e := judgeRun(module, run)
e := judgeVerdict(module, run) // the unlisted modules change only the words, never whether it passed
return e.failed == "" && e.couldNot == ""
}
@@ -346,7 +346,7 @@ func TestOneCompositionRunPerCandidateAndMachine(t *testing.T) {
sup := asks(2)
readers(runKeyOf("run-r3", "n1"), 2)
readers(runKeyOf("run-r3", "n2"), 2)
pe, _ := json.Marshal(mpr.PipelineEnded{V: 1, Pipeline: "run-r3.a", Module: "a", Branch: trunkBranch, Commit: commit, Outcome: mpr.PipelineEndedOutcomeSuperseded, Run: "r3", Steps: []mpr.StepResult{}})
pe, _ := json.Marshal(mpr.PipelineEnded{V: 1, Pipeline: "run-r3.a", Branch: trunkBranch, Source: 1, Outcome: mpr.PipelineEndedOutcomeSuperseded, Run: "r3", Movers: []mpr.MoverEnded{{Module: "a", Steps: []mpr.StepResult{}}}})
if _, err := b.js.Publish(b.ctx, "mesh.seat."+mpr.Seat+".event."+mpr.EventPipelineEnded+".n1", pe); err != nil {
t.Fatal(err)
}
@@ -3,7 +3,6 @@ package main
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
@@ -11,7 +10,6 @@ import (
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// The composition step (design 47 G §22, §354, §63): the assigner takes the seat mesh-wants' accepted kind `step`, the
@@ -35,13 +33,15 @@ type compositionSteps struct {
// run runs one step and answers what it came to; resume judges a step taken up at the start from its runs (takeUp).
run func(ctx context.Context, id string, run meshwants.StepRun) stepOutcome
resume func(ctx context.Context, id string, run meshwants.StepRun) stepOutcome
// validate runs one validate step and resumeValidate judges one taken up at the start (validatestep.go, design 47 H §745);
// nil takes no validate step.
validate func(ctx context.Context, id string, run meshwants.StepRun) stepOutcome
resumeValidate func(ctx context.Context, id string, run meshwants.StepRun) stepOutcome
// ended writes, once the step asked under id said its end, that time on its reader in each run naming it (A-470m); nil
// writes none.
ended func(id string, run meshwants.StepRun, at time.Time)
now func() time.Time
logf func(string, ...any)
// asker is the name the step's progress names as its asker, read when it is said (stepAskerOf).
asker func() string
// ticks is a ticker of every d, its channel and its stop (time.NewTicker); nil is the clock's. A test hands its own.
ticks func(d time.Duration) (<-chan time.Time, func())
mu sync.Mutex
@@ -49,32 +49,6 @@ type compositionSteps struct {
stops map[string]context.CancelFunc
}
// stepAskerOf is the asker a composition step's progress names: the one caller the seat mesh-wants' definition lists for its
// accepted kind step, read from the seat list when it is said, since that subject names no asker (design 47 G A-294, which
// corrects A-267). Empty while the seat list holds no definition naming exactly one.
func stepAskerOf(definition func() (seatdef.Definition, bool)) func() string {
return func() string {
d, ok := definition()
if !ok {
return ""
}
var one string
for _, m := range d.Accepts {
if m.Name != meshwants.AcceptStep || m.Callers == nil {
continue
}
for _, e := range m.Callers.List {
name, isSeat := strings.CutPrefix(e, seatdef.CallerSeatPrefix)
if !isSeat || (one != "" && one != name) {
return ""
}
one = name
}
}
return one
}
}
// progressEvery is how often a running composition step says its progress (design 47 G §496, A-262).
const progressEvery = time.Minute
@@ -118,18 +92,35 @@ func (p *stepPhase) get() string {
return p.phase
}
// take takes one ask of the accepted kind `step` by its id and body: a step that is no composition step, or an ask with no
// id, is left with a log line; one taken is run in its own goroutine and its end said.
// take takes one ask of the accepted kind `step` by its id and body: a step that is no composition or validate step, or an
// ask with no id, is left with a log line; one taken is run in its own goroutine and its end said.
func (c *compositionSteps) take(ctx context.Context, id string, data []byte) bool {
var run meshwants.StepRun
if err := json.Unmarshal(data, &run); err != nil || id == "" || run.Step != meshwants.StepRunStepComposition {
c.logf("a step ask that is no composition step with an id is left: %v", err)
err := json.Unmarshal(data, &run)
how := c.howOf(run.Step, false)
if err != nil || id == "" || how == nil {
c.logf("a step ask that is no composition or validate step with an id is left: %v", err)
return false
}
go c.say1(ctx, id, run, c.run, "")
go c.say1(ctx, id, run, how, "")
return true
}
// howOf is what runs a step, or judges it once taken up at the start: by its step, composition or validate; nil for another.
func (c *compositionSteps) howOf(step string, resumed bool) func(context.Context, string, meshwants.StepRun) stepOutcome {
switch {
case step == meshwants.StepRunStepComposition && resumed:
return c.resume
case step == meshwants.StepRunStepComposition:
return c.run
case step == meshwants.StepRunStepValidate && resumed:
return c.resumeValidate
case step == meshwants.StepRunStepValidate:
return c.validate
}
return nil
}
// say1 runs one step with how and says its end, naming in `shared` the runs it read (§723); again is, for an end said again, the
// ask of the run whose end makes it say again (sayEnd). A step whose wait was ended by its pipeline's supersede or cancel (leave)
// says nothing: the runner ended it already.
@@ -154,7 +145,7 @@ func (c *compositionSteps) say1(ctx context.Context, id string, run meshwants.St
stopWait()
}()
phase := &stepPhase{phase: meshwants.StepProgressEventPhaseFetch}
stop := c.sayProgress(id, phase)
stop := c.sayProgress(id, run.Asker, phase)
o := how(context.WithValue(ctx, phaseKey{}, phase), id, run)
stop()
if ctx.Err() != nil {
@@ -172,7 +163,11 @@ func (c *compositionSteps) sayEnd(id string, run meshwants.StepRun, started *tim
if started == nil {
started = &ended
}
end := meshwants.StepEnded{V: 1, ID: id, Pipeline: run.Pipeline, Step: meshwants.StepEndedStepComposition, Module: run.Module,
step := meshwants.StepEndedStepComposition
if run.Step == meshwants.StepRunStepValidate {
step = meshwants.StepEndedStepValidate
}
end := meshwants.StepEnded{V: 1, ID: id, Pipeline: run.Pipeline, Step: step, Module: run.Module,
Commit: run.Commit, Fingerprint: run.Fingerprint, Node: c.node, Outcome: o.Outcome, Said: o.Said, Warnings: o.Warnings,
Rerun: run.Rerun, By: run.By, Started: started, Ended: &ended, Shared: o.Shared}
msgID := id
@@ -222,7 +217,7 @@ func (c *compositionSteps) leave(ids []string) {
// sayProgress says the step's progress on the seat's step-progress.<node> once a minute until the returned stop is called (design
// 47 G §496, A-262): a ticker inside the running step, as the build seats' step runner says its own beat.
func (c *compositionSteps) sayProgress(id string, phase *stepPhase) (stop func()) {
func (c *compositionSteps) sayProgress(id, asker string, phase *stepPhase) (stop func()) {
ticks := c.ticks
if ticks == nil {
ticks = func(d time.Duration) (<-chan time.Time, func()) { t := time.NewTicker(d); return t.C, t.Stop }
@@ -239,7 +234,7 @@ func (c *compositionSteps) sayProgress(id string, phase *stepPhase) (stop func()
return
case <-tick:
at := c.now().UTC()
p := meshwants.StepProgressEvent{Ask: id, Asker: c.asker(), Phase: phase.get(), At: at, Shared: phase.waitsOn()}
p := meshwants.StepProgressEvent{Ask: id, Asker: asker, Phase: phase.get(), At: at, Shared: phase.waitsOn()}
if err := c.say(meshwants.EventStepProgress+"."+c.node, p, id+".progress."+at.Format(time.RFC3339Nano)); err != nil {
c.logf("saying the progress of the composition step %s: %v", id, err)
}
@@ -5,6 +5,7 @@ package main
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
@@ -241,3 +242,133 @@ func readInput(t *testing.T, nc *nats.Conn, in buildstep.RunInput) []byte {
}
return out.Bytes()
}
// Design 47 H §745 (acceptance test 117, the assigner's half; H-A-108), started whole on the bus: the assigner serves the step
// validate on the seat mesh-wants. A take-in whose manifest names an unknown field fails it `manifest-refused` naming it, the
// validator being the revision's own entry of the module holding the seat mesh-catalog, run on the Go build seat over the
// revision's manifests and the previous revision's; a take-in that changes a manifest with no problem passes it; a take-in whose
// entries make a cycle fails it `cycle` naming the cycle, with no validator asked.
func TestTheValidateStepServedWholeRefusesAManifestProblemAndACycle(t *testing.T) {
b := startBed(t, "")
nc, err := nats.Connect(b.srv.ClientURL())
if err != nil {
t.Fatal(err)
}
t.Cleanup(nc.Close)
const commit = "2222222222222222222222222222222222222222"
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,
nodebuildgo.SubjectStepEndedAll}, AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
indexer := meshcatalog.CatalogEntry{Module: "indexer", Repository: "novox/mesh-delivery", Commit: commit, Path: "modules/mesh-delivery-indexer",
Fp: "src2:ix", Serves: []string{"seat:" + meshcatalog.Seat + ".revision"}, Manifest: map[string]any{"module": "indexer"}, ManifestDigest: "d-ix"}
entry := func(module, digest string, manifest map[string]any, edges ...meshcatalog.Edge) meshcatalog.CatalogEntry {
manifest["module"] = module
return meshcatalog.CatalogEntry{Module: module, Manifest: manifest, ManifestDigest: digest, Edges: edges}
}
b.cat.mu.Lock()
b.cat.rev[trunkBranch] = 9
b.cat.at = map[string]map[int64][]meshcatalog.CatalogEntry{trunkBranch: {
6: {indexer, entry("web", "d-web-1", map[string]any{"version": "1"})},
7: {indexer, entry("web", "d-web-2", map[string]any{"version": "2", "colour": "red"})},
8: {indexer, entry("web", "d-web-3", map[string]any{"version": "3"})},
9: {indexer, entry("a", "d-a", map[string]any{}, meshcatalog.Edge{From: "a:x", To: "b:y", Kind: 3}, meshcatalog.Edge{From: "b:y", To: "a:x", Kind: 3}),
entry("b", "d-b", map[string]any{})},
}}
b.cat.mu.Unlock()
ended := make(chan meshwants.StepEnded, 4)
ends, err := nc.Subscribe("mesh.seat.mesh-wants.event.step-ended.n1", func(m *nats.Msg) {
var e meshwants.StepEnded
_ = json.Unmarshal(m.Data, &e)
ended <- e
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ends.Unsubscribe() })
subscribed(t, nc)
from := b.journal.mark()
b.start(t)
b.journal.await(t, from, "the composition step is heard on", "the steps served", 30*time.Second)
select {
case <-b.seatListRead:
case <-time.After(30 * time.Second):
t.Fatal("the assigner did not read the seat list within 30 s")
}
queue, _ := buildstep.AskStream(buildstep.AskGo)
worker, err := b.js.CreateOrUpdateConsumer(b.ctx, queue, jetstream.ConsumerConfig{Durable: "stand-in", FilterSubject: "mesh.seat.node-build-go.accept.check.mesh-wants", AckPolicy: jetstream.AckExplicitPolicy})
if err != nil {
t.Fatal(err)
}
ask := func(revision int64, module string, run func()) meshwants.StepEnded {
t.Helper()
id := fmt.Sprintf("validate-%d", revision)
step, _ := json.Marshal(meshwants.StepRun{Pipeline: fmt.Sprintf("%s.%d", trunkBranch, revision), Step: meshwants.StepRunStepValidate, Module: module,
Branch: trunkBranch, Revision: revision, Commit: commit})
msg := nats.NewMsg(meshwants.AcceptSubjectStep)
msg.Header.Set("x-event-id", id)
msg.Data = step
if err := nc.PublishMsg(msg); err != nil {
t.Fatal(err)
}
if run != nil {
run()
}
for {
select {
case e := <-ended:
if e.ID == id {
return e
}
case <-time.After(30 * time.Second):
t.Fatalf("the validate step of revision %d said no end", revision)
}
}
}
// The stand-in Go build seat runs the validator: it refuses a manifest naming the field colour, and accepts every other.
validator := func() {
t.Helper()
got, err := worker.Next(jetstream.FetchMaxWait(30 * time.Second))
if err != nil {
t.Fatalf("no validator run is asked: %v", err)
}
_ = got.Ack()
a, err := buildstep.DecodeStepAsk(got.Data())
if err != nil || a.Run == nil || a.Run.Program.Repository != "novox/mesh-delivery" || a.Run.Program.Commit != commit {
t.Fatalf("the validator's run ask %s: %v", got.Data(), err)
}
req, err := composer.Decode(readInput(t, nc, a.Run.Input))
if err != nil || len(req.Cases) != 2 || req.Cases[0].Name != changeCase || req.Cases[1].Name != beforeCase {
t.Fatalf("the validator's request: %+v %v", req, err)
}
v := composer.Verdict{V: composer.Version}
for _, c := range req.Cases {
reads := map[string]composer.ManifestRead{}
for module, m := range c.Manifests {
reads[module] = composer.ManifestRead{Accepted: true}
if strings.Contains(string(m.Raw), "colour") {
reads[module] = composer.ManifestRead{Refused: `unknown field "colour"`}
}
}
v.Cases = append(v.Cases, composer.CaseVerdict{Name: c.Name, Manifests: reads})
}
out, _ := json.Marshal(v)
end, _ := json.Marshal(buildstep.StepEnded{V: 1, ID: a.ID, Ask: a.ID, Asker: runAsker, Node: "b1", Outcome: buildstep.OutcomePassed, Output: string(out), At: time.Now().UTC()})
if _, err := b.js.Publish(b.ctx, nodebuildgo.SubjectStepEnded("b1"), end); err != nil {
t.Fatal(err)
}
}
if e := ask(7, "web", validator); e.Outcome != meshwants.StepEndedOutcomeFailed || !strings.HasPrefix(e.Said, reasonManifestRefused+": ") || !strings.Contains(e.Said, `web: unknown field "colour"`) {
t.Errorf("the validate step of a manifest naming an unknown field ended %+v", e)
}
if e := ask(8, "web", validator); e.Outcome != meshwants.StepEndedOutcomePassed {
t.Errorf("the validate step of a manifest with no problem ended %+v", e)
}
if e := ask(9, "a", nil); e.Outcome != meshwants.StepEndedOutcomeFailed || e.Said != reasonCycle+": a:x → b:y → a:x" {
t.Errorf("the validate step of a take-in making a cycle ended %+v", e)
}
if info, err := worker.Info(b.ctx); err != nil || info.NumPending != 0 {
t.Errorf("a validator is asked for the cycle: %+v %v", info, err)
}
}
@@ -3,7 +3,6 @@ package main
import (
"context"
"encoding/json"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"slices"
"strings"
"sync"
@@ -84,23 +83,7 @@ func TestARunningCompositionStepSaysItsProgress(t *testing.T) {
stopped := make(chan struct{})
at := time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
release := make(chan struct{})
// A-294: the asker is the one caller mesh-wants' definition lists for step, read from the seat list; none while unread
// or while it lists more than one.
runner := seatdef.Definition{Seat: meshwants.Seat, Accepts: []seatdef.Message{{Name: meshwants.AcceptStep,
Callers: &seatdef.Callers{List: []string{"seat:mesh-pipeline-runner"}}}}}
two := seatdef.Definition{Seat: meshwants.Seat, Accepts: []seatdef.Message{{Name: meshwants.AcceptStep,
Callers: &seatdef.Callers{List: []string{"seat:mesh-pipeline-runner", "seat:mesh-catalog"}}}}}
for _, d := range []struct {
def seatdef.Definition
read bool
want string
}{{runner, true, "mesh-pipeline-runner"}, {runner, false, ""}, {two, true, ""}} {
if got := stepAskerOf(func() (seatdef.Definition, bool) { return d.def, d.read })(); got != d.want {
t.Errorf("the asker of %+v (read %v) = %q, want %q", d.def.Accepts, d.read, got, d.want)
}
}
c := &compositionSteps{node: "n1", say: said.say, now: func() time.Time { return at }, logf: t.Logf,
asker: stepAskerOf(func() (seatdef.Definition, bool) { return runner, true }),
ticks: func(d time.Duration) (<-chan time.Time, func()) {
if d != time.Minute {
t.Errorf("the progress ticks every %s, want a minute", d)
@@ -113,7 +96,8 @@ func TestARunningCompositionStepSaysItsProgress(t *testing.T) {
<-release
return stepOutcome{Outcome: meshwants.StepEndedOutcomePassed}
}}
body, _ := json.Marshal(meshwants.StepRun{Pipeline: "main.4.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: "main"})
// A11/AC1 (design 47 H §752, H-A-88): with no callers in mesh-wants, the progress names the asker the step run carries.
body, _ := json.Marshal(meshwants.StepRun{Pipeline: "main.4", Step: meshwants.StepRunStepComposition, Module: "m", Branch: "main", Asker: "mesh-pipeline-runner"})
if !c.take(context.Background(), "ask-1", body) {
t.Fatal("the composition step is not taken")
}
@@ -1,454 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
wd "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs"
"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/meshwants"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
)
// A delivery is waited for mesh-wide (design 47 G §376, §389, A-189, A-246). At its start the assigner reads whole, from their first
// message, the streams of the catalog seat's version-released and of its own version-delivered (mesh-sdk process.FromFirst, A-233),
// and the watchman's machine-away and machine-back, never its state; then it hears them. A released version of a module is said
// version-delivered on the seat mesh-wants once, when every present machine placing it on the branch it is released from runs, healthy,
// the want the assigner wrote naming that version; a version no present machine places is not delivered. A dependent whose want
// changes fingerprint waits, by an edge of kind 2, 4 or 6, for its dependency's newest released version not yet said delivered, on
// the branch it is released from; on another branch no version is released and nothing waits. The wait is said wait-held, step
// delivery, bound 60 minutes from the version's release, kept in the state delivery-waits under the dependent's name, and said
// wait-ended when the version is delivered (ran) or released by hand (assigner_release, released).
// deliveryWaitBound is a dependent's delivery wait's bound, from its dependency's version-released.
const deliveryWaitBound = 60 * time.Minute
// Wait-ended's how of a delivery wait.
const (
deliveryWaitRan = "ran"
deliveryWaitReleased = "released"
)
// releaseHeard is one version-released heard: the version, each part's digest, the source revision and when it was said.
type releaseHeard struct {
Version string
Parts map[string]string
Source int64
At time.Time
}
// newestOf is the newest version of module released, the last heard of it in the stream's order.
func (r *releasedVersions) newestOf(module string) (releaseHeard, bool) {
r.mu.Lock()
defer r.mu.Unlock()
h, ok := r.newest[module]
return h, ok
}
// deliveredVersions are the version-delivered said, the assigner's own, by module and version: each is said once.
type deliveredVersions struct {
mu sync.Mutex
said map[string]bool
}
func (d *deliveredVersions) key(module, version string) string { return module + "@" + version }
// put takes one version-delivered in.
func (d *deliveredVersions) put(data []byte) error {
var e meshwants.VersionDeliveredEvent
if err := json.Unmarshal(data, &e); err != nil {
return fmt.Errorf("a version-delivered that is none: %w", err)
}
if e.Module == "" || e.Version == "" {
return fmt.Errorf("a version-delivered naming no module or version: %s", data)
}
d.mark(e.Module, e.Version)
return nil
}
func (d *deliveredVersions) mark(module, version string) {
d.mu.Lock()
defer d.mu.Unlock()
if d.said == nil {
d.said = map[string]bool{}
}
d.said[d.key(module, version)] = true
}
// has says whether version-delivered of module's version was said.
func (d *deliveredVersions) has(module, version string) bool {
d.mu.Lock()
defer d.mu.Unlock()
return d.said[d.key(module, version)]
}
// presenceOf reads one machine-away or machine-back: the machine and when it was said.
func presenceOf(data []byte) (string, time.Time, error) {
var e wd.MachineAwayEvent // machine-back has the same fields
if err := json.Unmarshal(data, &e); err != nil {
return "", time.Time{}, err
}
if e.Machine == "" {
return "", time.Time{}, fmt.Errorf("it names no machine: %s", data)
}
return e.Machine, e.At, nil
}
// hearDelivery reads whole, then follows, the four streams a delivery is judged from: version-released, version-delivered,
// machine-away and machine-back. A stream not heard is said as the assigner's finding, and what it carries is not known until
// the assigner starts again.
func hearDelivery(ctx context.Context, js jetstream.JetStream, w *world, wake func(), findings assign.Findings, logf func(string, ...any)) {
acct := process.Account{Node: thisNode, Module: assignment.Module()}
nh := notHeardWriter(findings, logf)
for _, s := range []struct {
stream, words string
take func([]byte) error
}{
{meshcatalog.StreamVersionReleased, "no want names a released version and no delivery is judged", w.released.put},
{meshwants.StreamVersionDelivered, "a version said delivered before is said again once it is judged", w.delivered.put},
{wd.StreamMachineAway, "no machine is known away, so a delivery waits for a machine that is away", func(data []byte) error {
m, at, err := presenceOf(data)
if err == nil {
w.heardPresence(m, true, at)
logf("%s is away (machine-away): a composition step does not compose it until its machine-back", m)
}
return err
}},
{wd.StreamMachineBack, "a machine once away is not known back", func(data []byte) error {
m, at, err := presenceOf(data)
if err == nil {
w.heardPresence(m, false, at)
logf("%s is back (machine-back): a composition step composes it again", m)
}
return err
}},
} {
take := s.take
cc, err := acct.HearSeatEvents(ctx, js, s.stream, func(m jetstream.Msg) {
if err := take(m.Data()); err != nil {
logf("%s is not kept: %v", m.Subject(), err)
}
if err := m.Ack(); err != nil {
logf("acknowledging %s: %v", m.Subject(), err)
}
wake()
}, logf, process.FromFirst())
if err != nil {
nh.NotHeard(s.stream, s.words+" until the assigner starts again", err)
continue
}
nh.Heard(s.stream)
go func() {
<-ctx.Done()
cc.Stop()
}()
}
}
// releaseBranch is the branch module's versions are released from: the first watched branch of its registration (§371).
func (p *passer) releaseBranch(module string) string {
if p.ends.following() {
return p.ends.branchOf(module, "")
}
return p.w.trunkName()
}
// placing is every machine placing module on the branch its versions are released from, sorted.
func (p *passer) placing(module string) []string {
branch := p.releaseBranch(module)
var out []string
for node, placed := range p.w.placedBranches()[module] {
if p.ends.following() {
placed = p.ends.branchOf(module, placed)
} else {
placed = p.w.trunkName() // the trunk-only form: every placement runs the trunk's
}
if placed == branch {
out = append(out, node)
}
}
sort.Strings(out)
return out
}
// deliveryStanding is where module's version stands: the present placing machines not yet running it healthy as its want names
// it, and the placing machines away.
func (p *passer) deliveryStanding(module, version string) (notRunning, away []string, placing int) {
gone := p.w.awayNow()
n := assign.Nodes{Running: p.w.runningNow()}
wanted := p.w.wantsOf()[module]
nodes := p.placing(module)
for _, node := range nodes {
if gone[node] {
away = append(away, node)
continue
}
want, ok := wanted[node]
if !ok || want.Removed || want.Version != version || !n.RunsHealthy(node, module, want.Fp) {
notRunning = append(notRunning, node)
}
}
return notRunning, away, len(nodes)
}
// judgeDelivered says version-delivered of each module's newest released version not said yet, once every present machine placing
// it runs it healthy; judged again at each pass, which each running, machine-away, machine-back and placement change wakes.
func (p *passer) judgeDelivered() {
for _, module := range p.releasedModules() {
rel, _ := p.w.released.newestOf(module)
if p.w.delivered.has(module, rel.Version) {
continue
}
notRunning, away, placing := p.deliveryStanding(module, rel.Version)
if placing == 0 || len(away) == placing || len(notRunning) > 0 {
continue
}
if err := p.sayDelivered(module, rel, away); err != nil {
p.logf("version-delivered of %s %s is not said, and is judged again at the next pass: %v", module, rel.Version, err)
}
}
}
// sayDelivered says version-delivered of module's release rel, with the machines away, and keeps it said.
func (p *passer) sayDelivered(module string, rel releaseHeard, away []string) error {
at := p.clock().UTC()
body := meshwants.VersionDeliveredEvent{V: keys.Version, Module: module, Version: rel.Version, Parts: rel.Parts, Away: away, At: &at}
if err := p.wantsSay(meshwants.EventVersionDelivered, body, fmt.Sprintf("%s.%s.%s.%s", meshwants.EventVersionDelivered, module, rel.Version, at.Format(time.RFC3339Nano))); err != nil {
return err
}
p.w.delivered.mark(module, rel.Version)
return nil
}
// releasedModules is every module a version-released was heard of, sorted.
func (p *passer) releasedModules() []string {
r := &p.w.released
r.mu.Lock()
defer r.mu.Unlock()
out := make([]string, 0, len(r.newest))
for m := range r.newest {
out = append(out, m)
}
sort.Strings(out)
return out
}
// deliveryWait is what a dependent waits for: its dependency, the version and the machines not yet running it.
type deliveryWait struct {
dependency string
rel releaseHeard
notRunning []string
away []string
}
// waitsForDelivery says whether module, whose want on its nodes changes to fp on branch, waits for a dependency's delivery: by
// each edge of kind 2, 4 or 6 into it in branch's catalog half, the dependency's newest released version on branch not yet said
// delivered. A want that changes no fingerprint waits for nothing; on a branch no version is released from, nothing waits.
func (p *passer) waitsForDelivery(module, fp, branch string, nodes []string) (deliveryWait, bool) {
wanted := p.w.wantsOf()[module]
changes := false
for _, node := range nodes {
if w, ok := wanted[node]; !ok || w.Removed || w.Fp != fp {
changes = true
}
}
if !changes || fp == "" {
return deliveryWait{}, false
}
var deps []string
for _, e := range p.w.edgesOf(branch, module) {
if e.Kind != 2 && e.Kind != 4 && e.Kind != 6 {
continue
}
dep, _, _ := strings.Cut(e.From, ":")
if dep != "" && dep != module && !slices.Contains(deps, dep) {
deps = append(deps, dep)
}
}
sort.Strings(deps)
for _, dep := range deps {
if p.releaseBranch(dep) != branch {
continue
}
rel, ok := p.w.released.newestOf(dep)
if !ok || p.w.delivered.has(dep, rel.Version) {
continue
}
notRunning, away, _ := p.deliveryStanding(dep, rel.Version)
return deliveryWait{dependency: dep, rel: rel, notRunning: notRunning, away: away}, true
}
return deliveryWait{}, false
}
// words is a delivery wait in plain words, as assigner_why_not and the status view say it.
func (d deliveryWait) words() string {
if len(d.notRunning) == 0 && len(d.away) > 0 {
return fmt.Sprintf("waiting for %s to be back", strings.Join(d.away, ", "))
}
return fmt.Sprintf("waiting for delivery of %s %s on %s", d.dependency, d.rel.Version, strings.Join(d.notRunning, ", "))
}
// deliveryWaitBody is the wait-held of module's delivery wait d.
func deliveryWaitBody(module, fp string, d deliveryWait, since time.Time) meshwants.Wait {
from := d.rel.At.UTC()
if from.IsZero() {
from = since.UTC()
}
return meshwants.Wait{Step: meshwants.WaitStepDelivery, Owner: meshwants.Seat, Module: module, Version: fp, Part: d.dependency,
On: d.dependency + "@" + d.rel.Version, Machines: d.notRunning, Since: since.UTC(), ClockFrom: &from, Bound: deliveryWaitBound.String(),
Words: d.words()}
}
// deliveryWaiting is one delivery wait the state delivery-waits keeps, by its dependent's name: the wait-held said, and a release
// by hand written by assigner_release.
type deliveryWaiting struct {
meshwants.Wait
// Released is set by assigner_release: the wait ends released and the dependent's want is written.
Released bool `json:"released,omitempty"`
}
// saidDeliveryWaits is every delivery wait the state delivery-waits holds, by module; a value that does not decode is said and left.
func (p *passer) saidDeliveryWaits() map[string]deliveryWaiting {
out := map[string]deliveryWaiting{}
for key, value := range p.w.read(buckets.DeliveryWaits()) {
var w deliveryWaiting
if err := json.Unmarshal(value, &w); err != nil || w.Module == "" {
p.logf("%s %s holds no delivery wait, left: %v", buckets.DeliveryWaits(), key, err)
continue
}
out[w.Module] = w
}
return out
}
// holdForDelivery says whether module's want, changing to fp on branch, is held for a dependency's delivery this pass: it says
// wait-held once and keeps it; a wait released by hand holds nothing; a wait that no longer holds is ended ran.
func (p *passer) holdForDelivery(ctx context.Context, module, fp, branch string, nodes []string) bool {
if p.kvs[buckets.DeliveryWaits()] == nil {
return false
}
key := keys.EscapeName(module)
said, was := p.saidDeliveryWaits()[module]
d, waits := p.waitsForDelivery(module, fp, branch, nodes)
switch {
case was && said.Released:
p.endDeliveryWait(ctx, key, said, deliveryWaitReleased) // the want is written now, so it changes nothing at the next pass
return false
case !waits:
if was {
p.endDeliveryWait(ctx, key, said, deliveryWaitRan)
}
return false
}
body := deliveryWaitBody(module, fp, d, p.clock())
if was && said.On == body.On && said.Version == fp && slices.Equal(said.Machines, body.Machines) {
return true
}
if was {
body.Since = said.Since
}
id := fmt.Sprintf("%s.delivery.%s.%s.%s", key, fp, body.On, strings.Join(body.Machines, ","))
if err := p.wantsSay(meshwants.EventWaitHeld, body, id); err != nil {
p.logf("the delivery wait of %s is not said, and is said at the next pass: %v", module, err)
return true
}
kept := deliveryWaiting{Wait: body}
p.put(ctx, buckets.DeliveryWaits(), key, func() ([]byte, error) { return json.Marshal(kept) })
p.logf("%s at %s on %s waits for the delivery of its dependency %s on %s: the rules write no want of it until then (design 47 G §376)", module, shortHex(fp), branch, body.On, strings.Join(body.Machines, ", "))
return true
}
// endDeliveryWait says wait-ended of a delivery wait with how and removes it from the state.
func (p *passer) endDeliveryWait(ctx context.Context, key string, w deliveryWaiting, how string) {
body := w.Wait
body.How = how
if err := p.wantsSay(meshwants.EventWaitEnded, body, key+".delivery."+body.Version+"."+how); err != nil {
p.logf("the end of the delivery wait of %s is not said, and is said at the next pass: %v", w.Module, err)
return
}
p.remove(ctx, buckets.DeliveryWaits(), key)
}
// againAsk is one ask of assigner_delivered_again, kept in the state delivered-again under its module (A-250): the version to say
// delivered again, who asked and why, and, while it does not hold, why not.
type againAsk struct {
Module string `json:"module"`
Version string `json:"version"`
By string `json:"by"`
Why string `json:"why"`
Waits string `json:"waits,omitempty"`
}
// releaseOf is the release heard of module's version.
func (r *releasedVersions) releaseOf(module, version string) (releaseHeard, bool) {
r.mu.Lock()
defer r.mu.Unlock()
if h, ok := r.newest[module]; ok && h.Version == version {
return h, true
}
for key, k := range r.seen {
if strings.HasPrefix(key, module+"@") && k.Version == version {
return releaseHeard{Version: version, Parts: k.Parts}, true
}
}
return releaseHeard{}, false
}
// deliveredAgain takes each ask of assigner_delivered_again, heard at once through the watch of the state delivered-again: it says
// version-delivered again when every present machine placing the module runs that version healthy and removes the ask, else keeps
// it with why it does not hold, which assigner_waits reads.
func (p *passer) deliveredAgain(ctx context.Context) {
if p.kvs[buckets.DeliveredAgain()] == nil {
return
}
for key, value := range p.w.read(buckets.DeliveredAgain()) {
var a againAsk
if err := json.Unmarshal(value, &a); err != nil || a.Version == "" {
p.logf("%s %s holds no ask, left: %v", buckets.DeliveredAgain(), key, err)
continue
}
module := a.Module
if module == "" {
module = key
}
waits := ""
rel, ok := p.w.released.releaseOf(module, a.Version)
notRunning, away, placing := p.deliveryStanding(module, a.Version)
switch {
case !ok:
waits = fmt.Sprintf("no version-released of %s %s is heard", module, a.Version)
case placing == 0:
waits = fmt.Sprintf("no machine places %s", module)
case len(away) == placing:
waits = fmt.Sprintf("every machine placing %s is away: %s", module, strings.Join(away, ", "))
case len(notRunning) > 0:
waits = fmt.Sprintf("%s %s does not run healthy on %s", module, a.Version, strings.Join(notRunning, ", "))
}
if waits == "" {
if err := p.sayDelivered(module, rel, away); err != nil {
p.logf("version-delivered of %s %s asked again is not said, and is asked at the next pass: %v", module, a.Version, err)
continue
}
p.logf("version-delivered of %s %s said again, asked by %s: %s", module, a.Version, a.By, a.Why)
p.remove(ctx, buckets.DeliveredAgain(), key)
continue
}
if a.Waits != waits {
a.Waits = waits
p.put(ctx, buckets.DeliveredAgain(), key, func() ([]byte, error) { return json.Marshal(a) })
}
}
}
@@ -1,188 +0,0 @@
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"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"
"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/meshwants"
"mesh-delivery-assigner/internal/buckets"
)
// Design 47 G §376, §389, §498, A-189, A-246: a released version is said version-delivered once, when every present machine placing
// it runs healthy the want naming it, a machine away named and not waited for, none when every placing machine is away; a dependent
// whose want changes fingerprint waits by an edge of kind 2, 4 or 6 for its dependency's newest released version not yet said
// delivered, said wait-held (step delivery, 60 minutes from the release) once and kept in delivery-waits, and wait-ended ran once
// the version is delivered; a kind-1 edge, or a dependency with no version released, waits for nothing; one released by hand ends
// released and its want is written.
func TestADependentWaitsForItsDependencysDelivery(t *testing.T) {
ctx := context.Background()
at := time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
waits := &memKV{values: map[string][]byte{}}
again := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): &memKV{values: map[string][]byte{}}, buckets.DeliveryWaits(): waits, buckets.DeliveredAgain(): again}, at)
p.logf = t.Logf
var events []said
p.publishWants = func(event string, body any, id string) error {
raw, _ := json.Marshal(body)
events = append(events, said{event, id, raw})
return nil
}
p.w.runningHeard = true
placeOn(t, p.w, "ace", "db", "app")
placeOn(t, p.w, "g14", "db")
fp := func(c string) string { return meshcatalogclient.SourcePrefix2 + strings.Repeat(c, 64) }
want := func(node, module, fp, version string) {
key, _ := mwc.WantKey(node, module)
raw, err := mwc.EncodeWant(mwc.Want{Fp: fp, Version: version, Self: true})
if err != nil {
t.Fatal(err)
}
p.w.put(buckets.Wants(), key, raw)
}
runs := func(node, module, fp string) {
raw, _ := json.Marshal(map[string]any{"v": 1, "node": node, "module": module, "fingerprint": fp, "at": at})
if err := p.w.hearRunning("running", raw); err != nil {
t.Fatal(err)
}
}
source := int64(3)
release := func(module, version string) {
source++
raw, _ := json.Marshal(meshcatalog.VersionReleasedEvent{V: 1, Module: module, Version: version, Source: source, At: &at,
Artifacts: []meshcatalog.VersionArtifact{{Artifact: "program", Digest: "sha256:d"}}})
if err := p.w.released.put(raw); err != nil {
t.Fatal(err)
}
}
saidOf := func(event string) []said {
var out []said
for _, e := range events {
if e.event == event {
out = append(out, e)
}
}
return out
}
want("ace", "app", fp("1"), "")
// No version of db is released: app's new fingerprint waits for nothing.
p.w.putEdges(trunkBranch, "app", []meshcatalog.Edge{{Kind: 4, From: "db:program", To: "app:program"}})
if p.holdForDelivery(ctx, "app", fp("2"), trunkBranch, []string{"ace"}) {
t.Fatal("app waits with no version of db released")
}
release("db", "1.1.0")
want("ace", "db", fp("d"), "1.1.0")
want("g14", "db", fp("d"), "1.1.0")
runs("ace", "db", fp("d"))
// A kind-1 edge orders nothing.
p.w.putEdges(trunkBranch, "app", []meshcatalog.Edge{{Kind: 1, From: "db:program", To: "app:program"}})
if p.holdForDelivery(ctx, "app", fp("2"), trunkBranch, []string{"ace"}) {
t.Fatal("a kind-1 edge holds app")
}
p.w.putEdges(trunkBranch, "app", []meshcatalog.Edge{{Kind: 4, From: "db:program", To: "app:program"}})
// app's want unchanged waits for nothing.
if p.holdForDelivery(ctx, "app", fp("1"), trunkBranch, []string{"ace"}) {
t.Fatal("app's unchanged want waits")
}
// g14 places db and does not run 1.1.0 yet: not delivered, and app's new version waits, said once.
p.judgeDelivered()
if !p.holdForDelivery(ctx, "app", fp("2"), trunkBranch, []string{"ace"}) || !p.holdForDelivery(ctx, "app", fp("2"), trunkBranch, []string{"ace"}) {
t.Fatal("app does not wait for db 1.1.0")
}
if len(saidOf(meshwants.EventVersionDelivered)) != 0 {
t.Fatalf("db is said delivered while g14 does not run it: %+v", events)
}
held := saidOf(meshwants.EventWaitHeld)
if len(held) != 1 {
t.Fatalf("wait-held said %d times, want once", len(held))
}
var w meshwants.Wait
_ = json.Unmarshal(held[0].body, &w)
if w.Step != meshwants.WaitStepDelivery || w.Part != "db" || w.Module != "app" || w.Version != fp("2") || w.Bound != "1h0m0s" ||
w.ClockFrom == nil || !w.ClockFrom.Equal(at) || len(w.Machines) != 1 || w.Machines[0] != "g14" || w.Words != "waiting for delivery of db 1.1.0 on g14" {
t.Errorf("the wait said is %+v", w)
}
if _, ok := waits.values["app"]; !ok {
t.Errorf("the wait is not kept in delivery-waits: %v", waits.values)
}
// g14 away: every present machine runs it, so it is delivered, g14 named away; once only.
p.w.heardPresence("g14", true, at)
p.judgeDelivered()
p.judgeDelivered()
delivered := saidOf(meshwants.EventVersionDelivered)
var d meshwants.VersionDeliveredEvent
if len(delivered) != 1 || json.Unmarshal(delivered[0].body, &d) != nil || d.Module != "db" || d.Version != "1.1.0" ||
len(d.Away) != 1 || d.Away[0] != "g14" || d.Parts["db:program"] != "sha256:d" {
t.Fatalf("version-delivered said %+v", delivered)
}
// The wait ends ran, and app's want goes on.
if p.holdForDelivery(ctx, "app", fp("2"), trunkBranch, []string{"ace"}) {
t.Fatal("app still waits once db 1.1.0 is delivered")
}
ended := saidOf(meshwants.EventWaitEnded)
if len(ended) != 1 || json.Unmarshal(ended[0].body, &w) != nil || w.How != deliveryWaitRan {
t.Errorf("wait-ended said %+v", ended)
}
if _, ok := waits.values["app"]; ok {
t.Error("the ended wait is kept")
}
// A newer release with every placing machine away is not delivered, and its wait says the machines it waits to be back.
release("db", "1.2.0")
p.w.heardPresence("ace", true, at)
p.judgeDelivered()
if len(saidOf(meshwants.EventVersionDelivered)) != 1 {
t.Error("a version is said delivered while every placing machine is away")
}
if !p.holdForDelivery(ctx, "app", fp("3"), trunkBranch, []string{"ace"}) {
t.Fatal("app does not wait for db 1.2.0")
}
held = saidOf(meshwants.EventWaitHeld)
if json.Unmarshal(held[len(held)-1].body, &w) != nil || w.Words != "waiting for ace, g14 to be back" {
t.Errorf("the wait while every machine is away says %q", w.Words)
}
// Released by hand (assigner_release writes it): the wait ends released and app's want is written.
var kept deliveryWaiting
_ = json.Unmarshal(waits.values["app"], &kept)
kept.Released = true
raw, _ := json.Marshal(kept)
p.w.put(buckets.DeliveryWaits(), "app", raw)
if p.holdForDelivery(ctx, "app", fp("3"), trunkBranch, []string{"ace"}) {
t.Fatal("a released wait holds app")
}
ended = saidOf(meshwants.EventWaitEnded)
if json.Unmarshal(ended[len(ended)-1].body, &w) != nil || w.How != deliveryWaitReleased {
t.Errorf("the released wait ended %+v", w)
}
// Presence: the later of machine-away and machine-back holds, whichever stream is read first.
p.w.heardPresence("ace", false, at.Add(time.Minute))
p.w.heardPresence("ace", true, at)
if p.w.awayNow()["ace"] || !p.w.online()["ace"] {
t.Error("an older machine-away read after a newer machine-back leaves ace away")
}
// A-250: an ask of assigner_delivered_again of 1.1.0, which ace (present) runs and g14 (away) does not, is said again and taken
// away; one of 1.2.0, which no machine runs, is kept with why.
ask := func(version string) {
raw, _ := json.Marshal(againAsk{Module: "db", Version: version, By: "op", Why: "the catalog missed it"})
p.w.put(buckets.DeliveredAgain(), "db", raw)
}
before := len(saidOf(meshwants.EventVersionDelivered))
ask("1.1.0")
p.deliveredAgain(ctx)
if len(saidOf(meshwants.EventVersionDelivered)) != before+1 || p.w.has(buckets.DeliveredAgain(), "db") {
t.Errorf("the ask of 1.1.0 said %d version-delivered and is kept %v", len(saidOf(meshwants.EventVersionDelivered))-before, p.w.has(buckets.DeliveredAgain(), "db"))
}
ask("1.2.0")
p.deliveredAgain(ctx)
var a againAsk
if json.Unmarshal(p.w.value(buckets.DeliveredAgain(), "db"), &a) != nil || a.Waits != "db 1.2.0 does not run healthy on ace" ||
len(saidOf(meshwants.EventVersionDelivered)) != before+1 {
t.Errorf("the ask of 1.2.0 = %+v", a)
}
}
@@ -0,0 +1,153 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"sync"
"time"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// engineWords is one node's key of the assigner's state engine-reads (design 47 H-A-104): the words its node-engine said it
// reads in the last manifest-reads-changed the assigner heard of it, and when the engine said them.
type engineWords struct {
Words []string `json:"words"`
At time.Time `json:"at"`
}
// engineReadsKept is what the assigner holds of its state engine-reads (design 47 H-A-104, §772): written when it hears the
// node-engine seat's manifest-reads-changed, and read back from the state's watch at the start, so a restart loses no node's
// words; no verb is asked and no node's record is read in its place.
type engineReadsKept struct {
mu sync.Mutex
by map[string]engineWords
// put writes one node's key; nil keeps the words in memory only (the state could not be opened).
put func(node string, value []byte) error
// changed wakes a pass when a node's words changed; nil wakes nothing.
changed func()
}
// heard keeps what one manifest-reads-changed says of its node: written into the state first, then held.
func (k *engineReadsKept) heard(e nodeengine.ManifestReadsChangedEvent) error {
at, err := time.Parse(time.RFC3339Nano, e.At)
if err != nil {
return fmt.Errorf("at %q is no RFC 3339 time", e.At)
}
v := engineWords{Words: slices.Clone(e.ManifestReads), At: at}
if k.put != nil {
raw, err := json.Marshal(v)
if err != nil {
return err
}
if err := k.put(e.Node, raw); err != nil {
return fmt.Errorf("the words of %s are not written into the state engine-reads: %w", e.Node, err)
}
}
k.hold(e.Node, v, false)
return nil
}
// take takes in one key of the state as its watch hands it: at the start every node's words, later the assigner's own writes
// (which change nothing) and a key dropped.
func (k *engineReadsKept) take(node string, raw []byte, deleted bool) error {
if deleted {
k.hold(node, engineWords{}, true)
return nil
}
var v engineWords
if err := json.Unmarshal(raw, &v); err != nil {
return fmt.Errorf("the key %s of the state engine-reads does not read: %w", node, err)
}
k.hold(node, v, false)
return nil
}
// hold sets one node's words, waking a pass when they changed.
func (k *engineReadsKept) hold(node string, v engineWords, deleted bool) {
k.mu.Lock()
old, had := k.by[node]
switch {
case deleted:
delete(k.by, node)
default:
if k.by == nil {
k.by = map[string]engineWords{}
}
k.by[node] = v
}
changed := (had && deleted) || (!deleted && (!had || !old.At.Equal(v.At) || !slices.Equal(old.Words, v.Words)))
k.mu.Unlock()
if changed && k.changed != nil {
k.changed()
}
}
// words is what node's engine said it reads, and whether the assigner holds its key; nil k holds none.
func (k *engineReadsKept) words(node string) ([]string, bool) {
if k == nil {
return nil, false
}
k.mu.Lock()
defer k.mu.Unlock()
v, ok := k.by[node]
return slices.Clone(v.Words), ok
}
// nodes is every node whose key the assigner holds, sorted.
func (k *engineReadsKept) nodes() []string {
if k == nil {
return nil
}
k.mu.Lock()
defer k.mu.Unlock()
return slices.Sorted(maps.Keys(k.by))
}
// engineReadsTool lists the assigner's state engine-reads: what each node's node-engine said it reads, and when.
const engineReadsTool = "assigner_engine_reads"
// readEngineReads is the state engine-reads, every node's key or node's alone.
func readEngineReads(st store, node string) (any, error) {
keys := []string{node}
if node == "" {
var err error
if keys, err = st.keys(engineReadsState); err != nil {
return nil, err
}
slices.Sort(keys)
}
out := map[string]engineWords{}
for _, key := range keys {
raw, _, found, err := st.get(engineReadsState, key)
if err != nil {
return nil, err
}
if !found {
if node != "" {
return nil, fmt.Errorf("the assigner holds no words of %s: its node-engine said no %s it heard", node, nodeengine.EventManifestReadsChanged)
}
continue
}
var v engineWords
if err := json.Unmarshal(raw, &v); err != nil {
return nil, errors.Join(fmt.Errorf("the key %s does not read", key), err)
}
out[key] = v
}
return map[string]any{"nodes": out}, nil
}
// engineReadsTools is the tool over the runtime's state.
func engineReadsTools(st store) []stdio.Tool {
return []stdio.Tool{{Name: engineReadsTool, Description: "What each node's node-engine says it reads of a manifest, as the " +
"assigner keeps it in its state engine-reads (design 47 H-A-104): per node the words of the last manifest-reads-changed " +
"it heard and when the engine said them. A node with no key states nothing the assigner heard, so its wants are held " +
"awaiting its hand placement (§772). With node, that node's key alone.",
Input: schema(map[string]string{"node": "one node; every node when left out"}, nil),
Run: func(a map[string]any) (any, error) { return readEngineReads(st, arg(a, "node")) }}}
}
@@ -6,7 +6,6 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"time"
@@ -35,13 +34,11 @@ type graphKeeper struct {
source int64
ok bool
said string
// cycled is the cycles last said (assigngraph.Cycles).
cycled string
// full says the next revision did not fit the store, so no want is written (graphfill.go); started says the first pass judged the fill.
full, started bool
// pins removes a revision that ceased to be current once nothing pins it (pins.go); nil keeps every revision.
pins *pinKeeper
// computed is the revision computed by the last pass, with its entries: the edges the wants wait on (actingwaits.go).
// revisions removes a revision that ceased to be current (revisions.go, H-A-86); nil keeps every revision.
revisions *revisionRemover
// computed is the revision computed by the last pass, with its entries: its edges.
computed assigngraph.Computed
}
@@ -53,21 +50,12 @@ func (p *passer) keepGraph(ctx context.Context) {
}
c := assigngraph.Compute(p.graphInputs())
g.computed = c
if p.ends != nil {
p.ends.setRunner(assigngraph.Runner(slices.Collect(maps.Values(c.Entries)))) // the runner's member of a group goes first (A-334)
}
for _, u := range c.Uncomputed {
if g.said != u {
g.said = u
p.logf("the assignment graph leaves out %s", u)
}
}
if cycles := strings.Join(c.Cycles, "; "); cycles != g.cycled {
g.cycled = cycles
if cycles != "" {
p.logf("the assignment graph holds a cycle among the acting waits, within one step or across steps: %s", cycles)
}
}
if !g.started {
g.started = true
p.fillAtStart(ctx)
@@ -95,8 +83,8 @@ func (p *passer) keepGraph(ctx context.Context) {
return
}
p.fillingAfter(ctx, used)
if g.pins != nil {
g.pins.judge() // the revision before ceased to be current
if g.revisions != nil {
g.revisions.judge() // the revision before ceased to be current
}
id := fmt.Sprintf("%s-%s-%d", meshwants.EventAssignmentRevision, rev.Kind, rev.Revision)
if err := p.wantsSay(meshwants.EventAssignmentRevision, assigngraph.Event(rev), id); err != nil {
@@ -131,16 +119,12 @@ func (p *passer) capabilityDigests() []meshwants.AssignmentRevisionCapabilitiesI
slices.Sort(known)
var out []meshwants.AssignmentRevisionCapabilitiesItem
for _, node := range known {
read := p.reads != nil && p.reads.Known(node)
reads, read := p.reads.words(node)
rec, recorded := records[node]
if !read && !recorded {
continue
}
var reads []string
if read {
reads = slices.Clone(p.reads.Reads([]string{node})[node])
slices.Sort(reads)
}
slices.Sort(reads)
item := meshwants.AssignmentRevisionCapabilitiesItem{Node: node, Readings: slices.Clone(rec.RunnerCapabilities),
Fingerprint: rec.RunnerFingerprint}
slices.Sort(item.Readings)
@@ -158,7 +142,7 @@ func (p *passer) capabilityDigests() []meshwants.AssignmentRevisionCapabilitiesI
// sayWanted says `wanted` for a want written or removed now, from the revision the pass keeps (A-61, A-67); with none kept, it is
// said in the log that it was not said. fp is the want's, and for a removal the fingerprint last wanted there.
func (p *passer) sayWanted(node, module, fp string, removed bool) {
func (p *passer) sayWanted(node, module, fp, pipeline string, removed bool) {
if p.publishWants == nil {
return
}
@@ -168,7 +152,7 @@ func (p *passer) sayWanted(node, module, fp string, removed bool) {
return
}
at := p.clock().UTC()
body := meshwants.WantedEvent{V: keys.Version, Node: node, Module: module, Fp: fp, Removed: removed, Revision: g.kept.Revision, Source: g.source, At: &at}
body := meshwants.WantedEvent{V: keys.Version, Node: node, Module: module, Fp: fp, Pipeline: pipeline, Removed: removed, Revision: g.kept.Revision, Source: g.source, At: &at}
event := strings.TrimPrefix(meshwants.SubjectWanted(keys.EscapeName(node), keys.EscapeName(module)), "mesh.seat."+meshwants.Seat+".event.")
id := fmt.Sprintf("wanted.%s.%s.%s.%t.%d.%s", keys.EscapeName(node), keys.EscapeName(module), fp, removed, g.kept.Revision, at.Format(time.RFC3339Nano))
if err := p.wantsSay(event, body, id); err != nil {
@@ -178,10 +162,9 @@ func (p *passer) sayWanted(node, module, fp string, removed bool) {
// namedBuild answers what a want of module at fp names of its build (design 47 G §379, §526, A-96): a kept build's or another watched
// branch's parts and keeping node from the builder's `build.ended`; for the trunk's entry (fp is the module's, trunkFP), the released
// version and the parts of the `version-released` of the module whose source is the one its fingerprint was built at, the entry's
// `fp-src` (A-419: a merge that does not rebuild the module leaves it so), or for an entry naming none the one whose parts are the
// digests its build.ended made (A-421). A trunk entry whose release is not heard is said, once, naming which was tried.
func (p *passer) namedBuild(module, trunkFP string, fpSrc int64, unreleased ...bool) func(fp string) (assign.KeptBuild, bool) {
// version and the parts of the `version-released` whose parts are the digests its build.ended made (A-421): the catalog stamps no
// source on an entry (design 47 H §764, H-A-48). A trunk entry whose release is not heard is said, once, naming which was tried.
func (p *passer) namedBuild(module, trunkFP string, unreleased ...bool) func(fp string) (assign.KeptBuild, bool) {
return func(fp string) (assign.KeptBuild, bool) {
if k, ok := p.w.ends.partsOf(module, fp); ok {
return k, true
@@ -206,25 +189,11 @@ func (p *passer) namedBuild(module, trunkFP string, fpSrc int64, unreleased ...b
p.unheardRelease(module, fp, "no assignment graph revision is kept yet, so no release is looked up")
return assign.KeptBuild{}, false
}
if fpSrc == 0 {
// No fp-src (its fingerprint moved with no merge): the release whose parts are what its build made (A-421).
if k, ok := p.w.released.withParts(module, p.w.ends.madeOf(module, fp)); ok {
return k, true
}
p.unheardRelease(module, fp, "its catalog entry names no fp-src, and no version-released of it names the parts its build.ended made")
return assign.KeptBuild{}, false
if k, ok := p.w.released.withParts(module, p.w.ends.madeOf(module, fp)); ok {
return k, true
}
k, ok := p.w.released.of(module, fpSrc)
if !ok {
// The release names the source its reservation was made at, which can be an earlier revision than the entry's
// fp-src (novox 2026-11-16: mesh-hand-acts 0.1.13 released from 962, its entry's fp-src 963): the release whose parts
// are exactly the digests this fingerprint's build made is this build's (A-421).
if k, ok = p.w.released.withParts(module, p.w.ends.madeOf(module, fp)); ok {
return k, true
}
p.unheardRelease(module, fp, fmt.Sprintf("no version-released of it from source %d, the one its fingerprint was built at, nor one naming the parts its build.ended made, is heard", fpSrc))
}
return k, ok
p.unheardRelease(module, fp, "no version-released of it names the parts its build.ended made")
return assign.KeptBuild{}, false
}
}
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"slices"
"strings"
"sync"
"time"
@@ -13,6 +14,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
)
@@ -148,11 +150,6 @@ func (h *halves) changed(branch, module string, raw json.RawMessage, deleted boo
func fromEntry(e meshcatalog.CatalogEntry) (meshcatalog.ModulesByModuleValue, graph.Node, *parsed) {
v := meshcatalog.ModulesByModuleValue{Commit: e.Commit, Fp2: e.Fp, Needs: e.Needs, None2: e.None, Packages: e.Packages,
Path: e.Path, Repository: e.Repository, Verdict: e.Verdict}
// The source revisions it was taken in at and its fingerprint was built at: the release of a trunk build is matched by the
// latter (design 47 G A-419).
if e.Inputs != nil {
v.Src, v.FpSrc = e.Inputs.Src, e.Inputs.FpSrc
}
n := graph.Node{FP: e.Fp, None: e.None, Repository: e.Repository, Path: e.Path, Bases: e.Bases, Provides: e.Provides, Requires: e.Requires,
Awaits: e.Awaits, Invokes: e.Invokes, Serves: e.Serves, LeftOut: e.LeftOut}
for p := range e.Packages {
@@ -196,3 +193,25 @@ func (h *halves) views() map[string]mcc.Half {
}
return out
}
// watchedOf is module's watched branches in its registration's order (the branch `register` named first, then each branch in the
// order `watch` added it). Once registrations are held, a module none names has none: it is unlisted (H-A-144). Only before the
// first registrations are held do the gate's source's branches stand in (the branches followed then), in the order the source
// gives them, by their names escaped as its keys are (design 47 G §532, H-A-143, H-A-144).
func (h *halves) watchedOf(module string) []string {
h.mu.Lock()
b := h.branches
h.mu.Unlock()
if b == nil {
return nil
}
if b.Registrations != nil && len(b.Registrations.All()) > 0 {
if reg, ok := b.Registrations.Registration(module); ok {
return slices.Clone(reg.Branches)
}
return nil
}
out := b.Followed()
slices.SortStableFunc(out, func(x, y string) int { return strings.Compare(keys.EscapeName(x), keys.EscapeName(y)) })
return out
}
@@ -3,6 +3,8 @@ package main
import (
"context"
"encoding/json"
"errors"
"slices"
"testing"
"time"
@@ -48,3 +50,45 @@ func TestAMeshThatNamesNoBranchSettlesTheAssignersFirstPass(t *testing.T) {
}
}
}
// Design 47 H-A-143, H-A-144, G §532: a module's watched branches are its registration's, in its order; once registrations are held a
// module none names has none; before the first registrations the gate's source's branches stand in, in the source's order.
func TestAModulesWatchedBranchesAreItsRegistrations(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
for _, tc := range []struct {
name string
regs []seat.Registration
module string
want []string
}{
{"its registration's order", []seat.Registration{{Module: "link2pay", Branches: []string{"nox-mesh", "main"}}}, "link2pay", []string{"nox-mesh", "main"}},
{"no registration names it", []seat.Registration{{Module: "link2pay", Branches: []string{"nox-mesh", "main"}}}, "checker", nil},
{"before the first registrations, the source's", []seat.Registration{}, "checker", []string{"main", "master"}},
} {
t.Run(tc.name, func(t *testing.T) {
call := func(key string, _ any) (json.RawMessage, error) {
switch key {
case mcc.RegistrationsVerb:
return json.Marshal(seat.RegistrationsAnswer{Registrations: tc.regs})
case mcc.SourceVerb:
return json.Marshal(map[string][]string{"branches": {"master", "main"}})
}
return nil, errors.New("not answered here")
}
reader := &views.ProcessReader{Module: "mesh-delivery-assigner", Call: call, Logf: t.Logf}
h := &halves{w: newWorld(), call: call, reader: reader, wake: func() {}, logf: t.Logf, ctx: ctx}
if err := h.follow(); err != nil {
t.Fatal(err)
}
for _, f := range reader.Followers()[:2] { // the registrations and the gate's source
if err := f.Start(ctx); err != nil {
t.Fatal(err)
}
}
if got := h.watchedOf(tc.module); !slices.Equal(got, tc.want) {
t.Errorf("the watched branches of %s are %v, want %v", tc.module, got, tc.want)
}
})
}
}
File diff suppressed because it is too large Load Diff
@@ -16,7 +16,6 @@ import (
"git.novox.be/novox/mesh-sdk/go/buscalls"
"io"
"log"
"maps"
"mesh-delivery-assigner/internal/assigngraph"
"mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
@@ -41,6 +40,7 @@ import (
"git.novox.be/novox/mesh-sdk/go/seatlist"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient/enginereads"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-assigner/internal/assign"
@@ -77,7 +77,6 @@ func main() {
var readBuckets = []string{
buckets.Grants,
buckets.Have,
buckets.Provisions,
}
// readFamilies are the states kept one bucket per node the assigner reads, each named in its manifest's reads: every
@@ -90,11 +89,11 @@ func ownBuckets() []string {
return []string{buckets.Asks(), buckets.Differences(),
buckets.Puts(), buckets.Wants(), plc.AssignmentsBucket(), plc.ProposalsBucket(),
plc.CandidatesBucket(), plc.PulsesBucket(), assign.FindingsBucket(), assign.PoliciesBucket(), plc.SeatHoldersBucket(),
engineReadsBucket(), retiredBucket(), copiesBucket(), writtenBucket(), buckets.Waits(), buckets.PutWaits(), buckets.DeliveryWaits(), buckets.DeliveredAgain(), buckets.Inputs(), buckets.CompositionRuns(), pinsBucket()}
engineReadsBucket(), retiredBucket(), copiesBucket(), writtenBucket(), buckets.Waits(), buckets.PutWaits(), buckets.Inputs(), buckets.CompositionRuns()}
}
// engineReadsState is the assigner's state of what each node's engine states it reads (ADR 0618 §3), one key `<node>`, as
// the verb manifest-reads last answered it or the fallback read it: what assigner_engine_reads lists and asks again.
// engineReadsState is the assigner's state of what each node's engine says it reads (design 47 H-A-104), one key `<node>`
// whose value is the words and the time of the last manifest-reads-changed heard of it: what assigner_engine_reads lists.
const engineReadsState = "engine-reads"
// engineReadsBucket is that state's bucket.
@@ -135,11 +134,8 @@ var keptStates = []announce.State{
{Name: writtenState, Readable: true},
{Name: buckets.WaitsState, Readable: true},
{Name: buckets.PutWaitsState, Readable: true}, // the put waits said (putwaits.go, design 47 G A-211)
{Name: buckets.DeliveryWaitsState, Readable: true}, // the delivery waits said (delivered.go, design 47 G A-246)
{Name: buckets.DeliveredAgainState, Readable: true}, // the asks of assigner_delivered_again (delivered.go, design 47 G A-250)
{Name: buckets.InputsState, Readable: true}, // read by the tool process alone: the verb input and assigner_inputs (design 47 G §354)
{Name: buckets.CompositionRunsState, Readable: true}, // the composition runs, read by the process and its tools (design 47 G §719, A-468c)
{Name: pinsState, Readable: true}, // the records pinning each assignment graph revision (design 47 G §579)
}
// kvSet is every bucket the assigner opened, by name.
@@ -168,12 +164,6 @@ func open(ctx context.Context, js process.BucketOpener, logf func(string, ...any
logf("the bucket %s cannot be opened (%v): it is bound once the bus says it was made", name, err)
continue
}
if name == buckets.Provisions && err != nil {
// The seat mesh-provisioner's state, with its own delivery (ADR 0570 §4): bound once the bus says it was made;
// until then no want waits for a provision, as before.
logf("the bucket %s cannot be opened (%v): it is bound once the bus says it was made", name, err)
continue
}
if name == assign.PoliciesBucket() && err != nil {
// The seat mesh-wants' state, new with it (ADR 0565 §7): bound once the bus says it was made; until then no
// person's policy is read, so the controller's beside each composition holds, as before.
@@ -187,8 +177,8 @@ func open(ctx context.Context, js process.BucketOpener, logf func(string, ...any
continue
}
if name == engineReadsBucket() && err != nil {
// New with ADR 0618 §3: without it the statements the verb answers are kept in memory only, and
// assigner_engine_reads lists nothing.
// Without it the words each manifest-reads-changed says are kept in memory only, and assigner_engine_reads
// lists nothing.
logf("the bucket %s cannot be opened (%v): what each node's engine reads is kept in memory only until it starts again", name, err)
continue
}
@@ -197,27 +187,12 @@ func open(ctx context.Context, js process.BucketOpener, logf func(string, ...any
logf("the bucket %s cannot be opened (%v): it is read by the tool process alone", name, err)
continue
}
if name == pinsBucket() && err != nil {
// New with the pins (design 47 G §579): without it no pin is kept and no revision is removed.
logf("the bucket %s cannot be opened (%v): no pin is kept and no revision removed until it starts again", name, err)
continue
}
if name == buckets.Waits() && err != nil {
// New with the wait on an outside cause (design 47 G §706): without it no wait is made, and a failing check is judged
// as before.
logf("the bucket %s cannot be opened (%v): no outside wait is kept until the assigner starts again", name, err)
continue
}
if name == buckets.DeliveredAgain() && err != nil {
// New with A-250: without it assigner_delivered_again is not taken until the assigner starts again.
logf("the bucket %s cannot be opened (%v): no version is said delivered again until the assigner starts again", name, err)
continue
}
if name == buckets.DeliveryWaits() && err != nil {
// New with A-246: without it no dependent waits for its dependency's delivery until the assigner starts again.
logf("the bucket %s cannot be opened (%v): no delivery wait is kept until the assigner starts again", name, err)
continue
}
if name == buckets.PutWaits() && err != nil {
// New with A-211: without it no put's wait is said until the assigner starts again.
logf("the bucket %s cannot be opened (%v): no put's wait is said until the assigner starts again", name, err)
@@ -246,8 +221,8 @@ func open(ctx context.Context, js process.BucketOpener, logf func(string, ...any
// states and those new with a delivery of their own, bound once made, and the two that choose the grants' source.
func startsWithout(name string) bool {
switch name {
case plc.SeatHoldersBucket(), buckets.Provisions, assign.PoliciesBucket(), assign.FindingsBucket(),
buckets.Puts(), engineReadsBucket(), retiredBucket(), writtenBucket(), buckets.Waits(), buckets.PutWaits(), buckets.DeliveryWaits(), buckets.DeliveredAgain(), buckets.Inputs(), pinsBucket():
case plc.SeatHoldersBucket(), assign.PoliciesBucket(), assign.FindingsBucket(),
buckets.Puts(), engineReadsBucket(), retiredBucket(), writtenBucket(), buckets.Waits(), buckets.PutWaits(), buckets.Inputs():
return true
}
return slices.Contains(seatBuckets(), name) || name == buckets.Grants
@@ -303,9 +278,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// The inputs of the composition steps it asks a build seat to run: the seat mesh-wants' verb input is answered here in chunks
// of the core connection, of any size (design 47 G §354, §712, A-237).
inputs := inputsOver(kvs[buckets.Inputs()], js, account.Module, logger.Printf)
// The seat list (seatlist.go), followed in follow over the connection and the hub: the verb input's callers are checked
// against the seat's definition it holds (A-186).
gate := seatlist.NewPart("assigner", seatListAgainCallers)
// The seat list (seatlist.go), followed in follow over the connection and the hub.
gate := seatlist.NewPart("assigner")
if inputs != nil {
inputs.dropAtStart() // the objects of keys another part deleted (A-465)
stopInput, err := said.AnswerSeat(meshwants.Seat, seatlist.Definition(gate.Reader, meshwants.Seat), map[string]process.SeatHandler{meshwants.VerbInput: inputs.verb(conn, buscalls.SeatAckWithin)})
@@ -388,14 +362,11 @@ func watched() []string {
buckets.Differences(),
buckets.Wants(),
assign.PoliciesBucket(),
buckets.Provisions,
plc.SeatHoldersBucket(),
engineReadsBucket(),
writtenBucket(),
buckets.Waits(),
buckets.PutWaits(),
buckets.DeliveryWaits(),
buckets.DeliveredAgain(), // its watch wakes a pass at once on an ask of assigner_delivered_again (A-250)
}
}
@@ -403,8 +374,6 @@ func watched() []string {
// each change; changes that come during a pass make one more. It returns when ctx ends or a watch ends.
func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber, kvs kvSet, say func(oc.Condition) error, findings assign.Findings, bus caller, iv *catalogViews, inputs *inputKeeper, gate *seatlist.Part, logger *log.Logger, getenv func(string) string) error {
w := newWorld()
// The callers' seat entries are resolved from the assigner's own seat-holders as it last read them (A-298).
gate.Holders(seatlist.HoldersIn(func() (map[string][]byte, error) { return w.read(plc.SeatHoldersBucket()), nil }))
dirty := make(chan struct{}, 1)
wake := func() {
select {
@@ -414,16 +383,11 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
}
errs := make(chan error, len(watched())+2)
settled := make(chan struct{}, len(watched())+2)
// What each node's engine reads (ADR 0618 §3, §4): asked through the seat's verb, kept in the state engine-reads, read
// from the node's record where the engine does not answer (the fallback, said in the journal).
reads := &enginereads.Keeper{Fallback: w.recordReads, Changed: wake, Logf: logger.Printf}
if bus != nil {
reads.Call = bus.CallKeptOn // a kept call, called again through a transport fault (ADR 0668 §1)
reads.Once = bus.CallOn // its fault keeps the fallback at once while the kept call asks on (ADR 0668 §3)
}
// What each node's engine reads (design 47 H-A-104): the words of its manifest-reads-changed, kept in the state
// engine-reads and read back from its watch, so a restart loses none; no verb is asked.
reads := &engineReadsKept{changed: wake}
if kv := kvs[engineReadsBucket()]; kv != nil {
reads.Put = func(node string, v []byte) error { _, err := kv.Put(ctx, node, v); return err }
reads.Delete = func(node string) error { return kv.Delete(ctx, node) }
reads.put = func(node string, v []byte) error { _, err := kv.Put(ctx, node, v); return err }
}
watch := func(name string, opts ...jetstream.WatchOpt) error {
kw, err := kvs[name].WatchAll(ctx, opts...)
@@ -459,7 +423,9 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
value = e.Value()
}
if name == engineReadsBucket() {
reads.Heard(e.Key(), value, value == nil) // it wakes a pass when a statement changed
if err := reads.take(e.Key(), value, value == nil); err != nil { // it wakes a pass when the words changed
logger.Printf("%v", err)
}
continue
}
w.putEntry(name, e.Key(), value, e.Revision(), e.Created())
@@ -586,7 +552,7 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
}
}
// And the two that choose where grants are read from, with the same delivery as the grants part that writes one.
for _, name := range []string{buckets.Grants, assign.PoliciesBucket(), buckets.Provisions, plc.SeatHoldersBucket()} {
for _, name := range []string{buckets.Grants, assign.PoliciesBucket(), plc.SeatHoldersBucket()} {
if kvs[name] == nil && js != nil {
name := name
process.AwaitBucket(ctx, js, nc, name, "until then the bucket is not read",
@@ -615,8 +581,14 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
}
}
p := &passer{kvs: kvs, w: w, logf: logger.Printf, say: say, findings: findings, said: map[string]bool{}, answeredAt: map[string]uint64{},
reads: reads, seats: gate, askForFile: getenv("MESH_ASSIGNER_ASK_OPERATOR_FOR_FILE")}
reads: reads, seats: gate, askForFile: getenv("MESH_ASSIGNER_ASK_OPERATOR_FOR_FILE"), listed: iv.listed}
p.askOperatorFor() // the setting ask-operator-for said once at the start (design 47 G A-425a)
// The setting tier-bound (design 47 H §751) and the one timer that wakes the pass at a tier's deadline (H-A-56).
tierBound, err := tierBoundSetting(getenv)
if err != nil {
return err
}
p.tierBound, p.tierWake = tierBound, wake
// 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.
if bus != nil && kvs[buckets.Waits()] != nil {
@@ -636,7 +608,6 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
logger.Printf("%s is not heard, so a wait on an outside cause is judged again only when its check changes: %v", subject, err)
}
}
p.outside.readStart()
}
if js != nil {
p.publishWants = wantsPublisher(ctx, js, thisNode)
@@ -648,27 +619,20 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
}
iv.candidates.Store(&keep)
// A held revert's running entry and its want's, asked of the seat mesh-catalog's verb entry (design 47 G §710, A-217).
p.entries = meshcatalogclient.NewEntries(iv.h.call)
p.entries.Changed = func(meshcatalogclient.EntryRow) { wake() }
// The pins of the revisions (pins.go, design 47 G §579): the gate's pinned, freed, heads-replaced and pins-stated
// on the hub, registered before it starts.
if kv := kvs[pinsBucket()]; kv != nil {
k := &pinKeeper{ctx: ctx, st: kvEnds{ctx, kv}, objects: objects, inUse: inUseOf(w), findings: findings, now: time.Now, logf: logger.Printf}
if err := k.made(); err != nil {
logger.Printf("the state %s is not marked made, so no revision is removed until it is: %v", pinsState, err)
}
if err := hearPins(hub, k); err != nil {
logger.Printf("a pin is not heard, so no revision is removed until the assigner starts again: %v", err)
} else {
p.graph.pins = k
k.watchUnpins(kv)
}
entryAsks, err := settingFile(getenv("MESH_ASSIGNER_ENTRY_ASKS_FILE"))
if err != nil {
return err
}
p.entries = entriesOf(iv.h.branches, iv.h.call, entryAsks, iv.writer, wake)
askAgainOnReconnect(ctx, nc, p.entries)
// The revisions that are not current are removed when one ceases to be current and once now (revisions.go,
// design 47 H §764, H-A-86).
p.graph.revisions = &revisionRemover{ctx: ctx, objects: objects, inUse: inUseOf(w), logf: logger.Printf}
p.graph.revisions.judge()
}
}
// The node-engine seat's manifest-reads-changed, for one node (ADR 0618 §4): that node is asked again, with no timer.
// Heard on the assigner's durable consumer on EVENTS, which the grants part makes from the manifest's consumes; where it
// is not there yet, a node is asked again only when it comes back online.
// The node-engine seat's manifest-reads-changed, for one node (design 47 H-A-104): its words are written into the state
// engine-reads. Heard on the assigner's durable consumer on EVENTS, which the grants part makes from the manifest's consumes.
if js != nil {
// The teller's ask-ended (issue 1966): an ask ended at the channel without an answer is written again; registered
// before hearReadsChanged starts the hub.
@@ -690,11 +654,8 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
logger.Printf("a pipeline's end or a registration is not heard, so the wants keep the trunk-only form until the assigner starts again: %v", err)
}
}
hearDelivery(ctx, js, w, wake, findings, logger.Printf) // version-released, version-delivered, machine-away and machine-back
hearReleases(ctx, js, w, wake, findings, logger.Printf) // version-released, machine-away and machine-back
hearBuilds(ctx, js, &w.ends, wake, findings, logger.Printf)
if err := hearTaken(hub, &w.taken, wake, logger.Printf); err != nil {
logger.Printf("the indexer's take-ins are not heard, so an entry held by an order edge waits until the assigner starts again: %v", err)
}
hearReadsChanged(ctx, js, hub, reads, findings, gate.EventsLive, logger.Printf)
hearRunning(ctx, js, w, wake, findings, logger.Printf)
}
@@ -704,9 +665,9 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
// The composition step (design 47 G §22, §354): the seat mesh-wants' accepted kind step, run by one run ask per machine.
if bus != nil && js != nil && inputs != nil && p.publishWants != nil && runs != nil {
run := &compositionRun{runs: runs, inputs: &compositionInputs{machines: w.machinesOf, callFile: bus.CallFile}, keeper: inputs, reads: &compositionReads{}, call: bus.CallKept,
trunk: trunkOf(iv, w.trunkName), running: w.runningOf, away: func(machine string) bool { return w.awayNow()[machine] }, put: runAskPublisher(js), ask: bus.CallFile, now: time.Now, logf: logger.Printf}
steps := &compositionSteps{node: thisNode, say: p.publishWants, run: run.run, resume: run.resume, ended: runs.stepEnded, now: time.Now, logf: logger.Printf,
asker: stepAskerOf(seatlist.Definition(gate.Reader, meshwants.Seat))}
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}
steps := &compositionSteps{node: thisNode, say: p.publishWants, run: run.run, resume: run.resume,
validate: run.validate, resumeValidate: run.resumeValidate, ended: runs.stepEnded, now: time.Now, logf: logger.Printf}
move := steps.move(ctx) // the readers a rerun carried (§727, A-470d)
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
@@ -804,45 +765,45 @@ func sayVia(ctx context.Context, js jetstream.JetStream) func(oc.Condition) erro
}
}
// readsChangedHandler is what the assigner does with each event manifest-reads-changed: acknowledges it, keeps what it says
// of the node (a statement older than it does not stand) and asks the node again.
func readsChangedHandler(reads *enginereads.Keeper, logf func(string, ...any)) func(jetstream.Msg) {
// readsChangedHandler is what the assigner does with each event manifest-reads-changed: writes the words it says of its node
// into the state engine-reads, then acknowledges it; an event not written is not acknowledged, so the bus delivers it again.
func readsChangedHandler(reads *engineReadsKept, logf func(string, ...any)) func(jetstream.Msg) {
return func(m jetstream.Msg) {
node, ours, err := enginereads.NodeOf(m.Subject(), m.Data())
if ours && err == nil {
var e nodeengine.ManifestReadsChangedEvent
if e, err = enginereads.DecodeChanged(m.Data()); err == nil {
if err = reads.heard(e); err != nil {
logf("%s of %s: %v", enginereads.Event, node, err)
if nerr := m.Nak(); nerr != nil {
logf("not acknowledging %s: %v", m.Subject(), nerr)
}
return
}
}
}
if ours && err != nil {
logf("%s holds what is not %s, and is not kept: %v", m.Subject(), enginereads.Event, err)
}
if err := m.Ack(); err != nil {
logf("acknowledging %s: %v", m.Subject(), err)
}
node, ours, err := enginereads.NodeOf(m.Subject(), m.Data())
switch {
case !ours:
case err != nil:
logf("%s holds what is not %s, and %s is asked again all the same: %v", m.Subject(), enginereads.Event, node, err)
reads.AskNode(node, enginereads.Event+" that does not read")
default:
// What the event says is kept first: a statement older than it does not stand while the node is asked again.
if e, derr := enginereads.DecodeChanged(m.Data()); derr == nil {
reads.HeardChanged(e)
}
reads.AskNode(node, enginereads.Event)
}
}
}
// hearReadsChanged hears the node-engine seat's event manifest-reads-changed on the assigner's one hub of its durable
// consumer on EVENTS, and asks the node it names again; the hub also hands the indexer's views to the followers of
// consumer on EVENTS, and keeps the words of the node it names; the hub also hands the indexer's views to the followers of
// indexerViews, and starts once both are registered.
func hearReadsChanged(ctx context.Context, js jetstream.JetStream, hub *process.EventHub, reads *enginereads.Keeper, findings assign.Findings, live func(), logf func(string, ...any)) {
func hearReadsChanged(ctx context.Context, js jetstream.JetStream, hub *process.EventHub, reads *engineReadsKept, findings assign.Findings, live func(), logf func(string, ...any)) {
account := process.Account{Node: thisNode, Module: assignment.Module()}
w := notHeardWriter(findings, logf)
handle := readsChangedHandler(reads, logf)
err := hub.Handle(enginereads.SubjectPrefix+"*", handle)
// At each bind every node the assigner holds a statement of is asked again: an event said before its consumer existed
// is not delivered to it (issue 1966 note 155: ace's bootstrapped statement stood; ADR 0668 §4).
hub.OnBound(reads.AtBind(func() []string { return slices.Sorted(maps.Keys(reads.Statements())) }))
if err == nil {
err = hub.Start(ctx, js, account)
}
if err != nil {
w.NotHeard(process.EventsStream, enginereads.Event+" is not heard until the assigner starts again (a node is asked again when it comes back online)", err)
w.NotHeard(process.EventsStream, enginereads.Event+" is not heard until the assigner starts again, so no node's new words are kept", err)
return
}
w.Heard(process.EventsStream)
@@ -857,3 +818,35 @@ func hearReadsChanged(ctx context.Context, js jetstream.JetStream, hub *process.
hub.Stop()
}()
}
// entriesOf are the catalog entries the passer asks by fingerprint: the followed branches' own, so each catalog-revision asks
// again an entry whose ask failed to reach the holder, at most asks times (the setting entry-asks, 0 its default), and the
// assigner's finding writer writes entry-not-found and entry-unanswered of them (design 47 H, H-A-60). Each change wakes a pass.
func entriesOf(b *meshcatalogclient.Branches, call meshcatalogclient.Call, asks int, w views.WireWriter, wake func()) *meshcatalogclient.Entries {
if b == nil || b.Entries == nil {
b = &meshcatalogclient.Branches{Entries: meshcatalogclient.NewEntries(call)}
}
b.Entries.Asks = asks
if w == nil {
b.Entries.Changed = func(meshcatalogclient.EntryRow) { wake() }
return b.Entries
}
b.WriteEntryFindings(w, func(meshcatalogclient.EntryRow) { wake() })
return b.Entries
}
// askAgainOnReconnect asks the entries again whose ask failed each time the assigner's link to the bus opens again (design 47
// H, H-A-60), after whatever the connection already does then.
func askAgainOnReconnect(ctx context.Context, nc process.Subscriber, e *meshcatalogclient.Entries) {
conn, ok := nc.(*nats.Conn)
if !ok || conn == nil {
return
}
before := conn.Opts.ReconnectedCB
conn.SetReconnectHandler(func(c *nats.Conn) {
if before != nil {
before(c)
}
e.AskAgain(ctx)
})
}
@@ -16,6 +16,7 @@ import (
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strings"
"testing"
@@ -26,6 +27,7 @@ import (
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/seatlist"
@@ -125,7 +127,7 @@ func TestOpensWhatItsManifestNames(t *testing.T) {
}
kvs[buckets.Puts()].(*watchKV).closed = true
kvs[buckets.Wants()].(*watchKV).wrote = wrote
go follow(ctx, nil, nil, kvs, func(oc.Condition) error { return nil }, assign.Findings{}, nil, nil, nil, seatlist.NewPart("assigner", seatListAgainCallers), log.New(io.Discard, "", 0), func(string) string { return "" })
go follow(ctx, nil, nil, kvs, func(oc.Condition) error { return nil }, assign.Findings{}, nil, nil, nil, seatlist.NewPart("assigner"), log.New(io.Discard, "", 0), func(string) string { return "" })
select {
case key := <-wrote:
if key != "want.ace.node" {
@@ -209,3 +211,43 @@ func putInto(into map[string][]byte) func(mcseat.Finding) error {
return err
}
}
// fakeWire is a views part's finding writer that hands each written finding's kind on.
type fakeWire struct{ written chan string }
func (f fakeWire) WriteWire(_ context.Context, finding map[string]any) error {
k, _ := finding["kind"].(string)
f.written <- k
return nil
}
func (fakeWire) Clear(context.Context, string, string, string, string) error { return nil }
func (fakeWire) ModuleNode() (string, string) { return "mesh-delivery-assigner", "n1" }
// H-A-60: the assigner's entries are asked again to the setting entry-asks, then written through its finding writer as the
// finding entry-unanswered.
func TestAnUnreachedEntryEndsInTheAssignersFindingEntryUnanswered(t *testing.T) {
ctx := context.Background()
unreached := func(string, any) (json.RawMessage, error) { return nil, errors.New("no responders") }
w := fakeWire{written: make(chan string, 4)}
e := entriesOf(nil, unreached, 1, w, func() {})
if e.Asks != 1 {
t.Fatalf("entry-asks %d, want 1 from the setting", e.Asks)
}
e.Need(ctx, "src2:u")
deadline := time.Now().Add(5 * time.Second)
for {
select {
case kind := <-w.written:
if kind != meshcatalogclient.EntryUnansweredKind {
t.Fatalf("the finding written is %q, want %s", kind, meshcatalogclient.EntryUnansweredKind)
}
return
default:
}
if time.Now().After(deadline) {
t.Fatal("no finding entry-unanswered is written past the bound")
}
e.AskAgain(ctx)
runtime.Gosched()
}
}
@@ -1,296 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"strconv"
"sync"
"git.novox.be/novox/mesh-contracts/go/seats/meshbroker"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
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/meshdelivery"
seat "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/process"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"mesh-delivery-assigner/internal/acting"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assigngraph"
"mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
)
// The three order edges of a delivery that crosses a form change (design 47 G §298, A-245, A-258, A-259, A-260). Each is an acting wait of the
// assigner, kept in the state `waits` under `order.<node>.<module>.<part>` beside the acting waits, in the step placing, said as wait-held
// when a want is held for it and wait-ended (ran, released, replaced) when it moves; assigner_waits reads them and assigner_release with
// how `now` releases them, as it does an acting wait. The holders of the seats are read from the seat holders the assignments compose
// (assignment.SeatHoldersOf), never named:
// - the node-backup holder's and the bus module's (the holder of the seat mesh-broker) new versions run before a module whose kept data's
// form changes is moved, since the restore point needs both (OrderBackup);
// - at a revert a node's node-engine goes back last on that node, after every module it restores there runs the reverted build, which it
// starts only once it has said `restored` (OrderEngineLast);
// - the reverted assigner and gate are wanted only once the indexer's take-in.taken of the trunk branch names a source revision at least
// the trunk's head, the highest `src` of the trunk branch's module values (OrderTakenIn, A-260).
// takenSubject is the indexer's event take-in.taken on its own stream, as the manifest's consumes names it.
var takenSubject = process.ModuleStreamSubject(buckets.IndexerModule, "take-in.taken")
// takenSources are the newest source revisions a take-in.taken named, by watched branch, as heard (hearBuildsAndReleases).
type takenSources struct {
mu sync.Mutex
own map[string]int64
}
// put takes one take-in.taken in. A hand drop, and a taken with no source revision (one said before G), take nothing in.
func (t *takenSources) put(data []byte) error {
var e meshcatalog.TakeInTaken
if err := json.Unmarshal(data, &e); err != nil {
return fmt.Errorf("a take-in.taken that is none: %w", err)
}
if e.Dropped || e.Source == 0 || e.Branch == "" {
return nil
}
t.mu.Lock()
defer t.mu.Unlock()
if t.own == nil {
t.own = map[string]int64{}
}
t.own[e.Branch] = max(t.own[e.Branch], e.Source)
return nil
}
// of is the newest source revision of branch taken in; 0 before one is heard.
func (t *takenSources) of(branch string) int64 {
t.mu.Lock()
defer t.mu.Unlock()
return t.own[branch]
}
// orderEdge is one order edge held on module's want on node: part's version fp must run on partNode (OrderBackup, OrderEngineLast), or the
// trunk's source revision source be taken in (OrderTakenIn).
type orderEdge struct {
node, module, part, partNode, fp, entry, order string
source int64
}
func (e orderEdge) key() string { return acting.OrderKey(e.node, e.module, e.part) }
func (e orderEdge) acting() assign.ActingEdge {
return assign.ActingEdge{Node: e.partNode, Part: e.part, Fp: e.fp, Step: seatdef.StepPlace}
}
// orderRuns says an order edge is met: its part runs the version, or the source revision is taken in.
func (p *passer) orderRuns(n assign.Nodes, e orderEdge) bool {
if e.order == acting.OrderTakenIn {
return p.w.taken.of(p.w.trunkName()) >= e.source
}
return n.Runs(e.acting())
}
// seatHolders are the holders of each seat as the assignments compose them, by seat name.
func (p *passer) holdersBySeat() map[string][]mma.SeatHoldersHoldersItem {
out := map[string][]mma.SeatHoldersHoldersItem{}
for _, sh := range assignment.SeatHoldersOf(p.w.assignments()) {
out[sh.Seat] = append(out[sh.Seat], sh.Holders...)
}
return out
}
// orderEdgesOf computes §298's edges on the wants of module m on each of its nodes, into p.orders. wanted is m's wants by node; trunk the
// trunk's module values. A node that has no running build heard, runs m at its trunk version already, or is wanted that version already
// has none: nothing moves. It answers, by node, whether an edge still stands that cannot be recorded as a wait because the catalog entry
// it reads is not answered yet (asked, and its answer wakes a pass): the want is held meanwhile, never written across a form change unread.
func (p *passer) orderEdgesOf(ctx context.Context, m assign.Module, wanted map[string]mwc.Want, trunk map[string]meshcatalog.ModulesByModuleValue) map[string]bool {
unread := map[string]bool{}
p.orderVisited[m.Name] = true
if m.FP == "" || p.graph == nil || p.entries == nil {
return unread
}
var holders map[string][]mma.SeatHoldersHoldersItem
for _, node := range m.Nodes {
if w, ok := wanted[node]; ok && !w.Removed && w.Fp == m.FP {
continue // the version is wanted already: nothing moves, so nothing waits
}
run, heard := p.w.runningOf(node, m.Name)
if !heard || run.Stopped || run.Fingerprint == "" || run.Fingerprint == m.FP {
continue
}
if holders == nil {
holders = p.holdersBySeat()
}
held := func(seatName string) bool {
for _, h := range holders[seatName] {
if h.Module == m.Name && h.Node == node {
return true
}
}
return false
}
add := func(e orderEdge) {
e.node, e.module, e.entry = node, m.Name, m.FP
p.orders[e.key()] = e
}
// 1. a kept data's form changes: the restore point needs the new node-backup holder and bus module.
changes, known := p.formChange(ctx, m.Name, run.Fingerprint, m.FP)
if !known {
unread[node] = true
}
if len(changes) > 0 {
for seatName, onNode := range map[string]bool{catalogue.BackupSeat: true, meshbroker.Seat: false} {
for _, h := range holders[seatName] {
if h.Module == m.Name || (onNode && h.Node != node) || trunk[h.Module].Fp2 == "" {
continue
}
add(orderEdge{part: h.Module, partNode: h.Node, fp: trunk[h.Module].Fp2, order: acting.OrderBackup})
}
}
}
if !held(nodeengine.Seat) && !held(mma.Seat) && !held(meshdelivery.Seat) {
continue
}
reverted, err := assigngraph.Reverted(ctx, p.graph.objects, node, m.Name, run.Fingerprint, m.FP)
if err != nil {
p.logf("whether the want of %s on %s at %s is a revert is not read: %v", m.Name, node, m.FP, err)
continue
}
if !reverted {
continue
}
// 2. at a revert the node-engine goes back last on its node: after every module that is set back there across a form change runs.
if held(nodeengine.Seat) {
for module, byNode := range p.w.wantsOf() {
// What it is set back to is its trunk version, which the rules write as its want in this pass.
target := trunk[module].Fp2
if w, ok := byNode[node]; module == m.Name || !ok || w.Removed || target == "" {
continue
}
xrun, heard := p.w.runningOf(node, module)
if !heard || xrun.Stopped || xrun.Fingerprint == "" || xrun.Fingerprint == target {
continue
}
if back, err := assigngraph.Reverted(ctx, p.graph.objects, node, module, xrun.Fingerprint, target); err != nil || !back {
continue
}
xchanges, known := p.formChange(ctx, module, xrun.Fingerprint, target)
if !known {
unread[node] = true
}
if len(xchanges) > 0 {
add(orderEdge{part: module, partNode: node, fp: target, order: acting.OrderEngineLast})
}
}
}
// 3. the reverted assigner and gate wait for the indexer to take in the trunk's head.
if held(mma.Seat) || held(meshdelivery.Seat) {
var head int64
for _, v := range p.w.trunkOf(p.w.trunkName()) {
head = max(head, v.Src)
}
if head > 0 {
add(orderEdge{part: buckets.IndexerModule, fp: strconv.FormatInt(head, 10), source: head, order: acting.OrderTakenIn})
}
}
}
return unread
}
// orderActing is the order edges of module on node that still hold its want, as acting edges: those not met, and not released by hand. A
// node whose catalog entry is not read yet holds its want too, on a stand-in edge no part runs.
func (p *passer) orderActing(module string, released map[string]bool, unread map[string]bool, n func() assign.Nodes) func(node string) []assign.ActingEdge {
return func(node string) []assign.ActingEdge {
var out []assign.ActingEdge
nodes := n()
for _, e := range p.orders {
if e.module == module && e.node == node && !released[e.key()+"@"+e.fp] && !p.orderRuns(nodes, e) {
out = append(out, assign.ActingEdge{Node: e.partNode, Part: e.part, Fp: e.fp, Step: seatdef.StepPlace})
}
}
if unread[node] {
out = append(out, assign.ActingEdge{Node: node, Part: "the catalog entry", Step: seatdef.StepPlace})
}
return out
}
}
// orderWaits keeps the order waits after the pass's wants, as actingWaits keeps the acting waits: it starts the wait of each edge not met,
// ends the wait of one that ran, was replaced or was released, and says each.
func (p *passer) orderWaits(ctx context.Context, n assign.Nodes, wanted map[string]map[string]mwc.Want) {
if p.kvs[buckets.Waits()] == nil {
return
}
now := p.clock()
kept := p.w.read(buckets.Waits())
trunk := p.w.trunk()
if p.orderSaid == nil {
p.orderSaid = map[string]bool{}
}
standing := map[string]bool{}
for key, e := range p.orders {
if w, ok := wanted[e.module][e.node]; ok && !w.Removed && w.Fp == e.entry {
continue
}
if p.orderRuns(n, e) {
continue
}
standing[key] = true
if raw := kept[key]; raw != nil {
if w, err := acting.Decode(raw); err == nil && w.Entry == e.entry && w.Fp == e.fp {
if !w.Released && !p.orderSaid[key] {
// A wait still held after a restart is said again, as wait-held (A-260).
if err := p.wantsSay(seat.EventWaitHeld, acting.Body(w, assignment.Module()), key+"."+e.fp+"."+e.entry+".again"); err != nil {
p.logf("the wait of %s on %s for %s is not said again, and is said at the next pass: %v", e.module, e.node, e.part, err)
} else {
p.orderSaid[key] = true
}
}
p.actingReleaseSaid(ctx, key, w)
continue
}
}
if !n.Online[e.node] {
continue // a node away holds only itself, and its clock has not started (§268)
}
w := acting.Wait{Step: seatdef.StepPlace, Node: e.node, Module: e.module, Part: e.part, PartNode: e.partNode, Fp: e.fp, Entry: e.entry, Order: e.order,
Since: now, ClockFrom: now, Bound: acting.BoundOf(seat.Edge{Step: seatdef.StepPlace}).String()}
if err := p.wantsSay(seat.EventWaitHeld, acting.Body(w, assignment.Module()), key+"."+e.fp+"."+e.entry); err != nil {
p.logf("the wait of %s on %s for %s is not said, and is said at the next pass: %v", e.module, e.node, e.part, err)
continue
}
p.put(ctx, buckets.Waits(), key, func() ([]byte, error) { return acting.Encode(w) })
p.orderSaid[key] = true
}
for key, raw := range kept {
if !acting.IsOrder(key) || standing[key] {
continue
}
w, err := acting.Decode(raw)
if err != nil {
continue
}
if _, there := trunk[w.Module]; there && !p.orderVisited[w.Module] {
continue // the module was not looked at in this pass (no pipeline passed for it yet): its wait stands as kept
}
how := acting.HowRan
switch e, there := p.orders[key]; {
case w.Released:
how = acting.HowReleased
case there && e.fp != w.Fp, !there && wanted[w.Module][w.Node].Fp != w.Entry:
how = acting.HowReplaced
}
if !w.EndSaid {
body := acting.Body(w, assignment.Module())
body.How = how
if err := p.wantsSay(seat.EventWaitEnded, body, key+"."+w.Fp+"."+w.Entry+"."+how); err != nil {
p.logf("the end of the wait of %s on %s for %s is not said, and is said at the next pass: %v", w.Module, w.Node, w.Part, err)
continue
}
}
p.remove(ctx, buckets.Waits(), key)
delete(p.orderSaid, key)
}
}
@@ -1,351 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"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/seats/meshbroker"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"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"
"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/meshdelivery"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"mesh-delivery-assigner/internal/acting"
"mesh-delivery-assigner/internal/assigngraph"
plc "mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
)
// orderFP is a fingerprint of the form the trunk keeps, made of one letter.
func orderFP(c string) string {
return meshcatalogclient.SourcePrefix2 + strings.Repeat(fmt.Sprintf("%x", c[0]&15), 64)
}
// orderMod is one module of an order test: the fingerprint it runs on ace and the one the trunk holds, the form of its kept data at each
// fingerprint (0: it keeps none), the seats it holds and the source revision of its trunk value.
type orderMod struct {
name string
run, trunk string
forms map[string]int
holds []string
src int64
}
type orderFixture struct {
t *testing.T
p *passer
wants *memKV
events []string
bodies []meshwants.Wait
answers chan struct{}
}
// newOrderFixture is a pass on node ace, which composes its own modules, with each module running its fingerprint healthy, built and
// granted at the trunk's, an older want, the catalog's entries answered and each held seat as the assignments say it. history lists the
// fingerprints of each module by assignment graph revision, oldest first (the objects Reverted reads).
func newOrderFixture(t *testing.T, mods []orderMod, history ...map[string]string) *orderFixture {
t.Helper()
ctx := context.Background()
f := &orderFixture{t: t, wants: &memKV{values: map[string][]byte{}}, answers: make(chan struct{}, 64)}
f.p = newPasser(kvSet{buckets.Wants(): f.wants, buckets.Asks(): &memKV{values: map[string][]byte{}}, buckets.Waits(): &memKV{values: map[string][]byte{}}}, time.Now())
p := f.p
p.logf = t.Logf
p.say = func(oc.Condition) error { return nil }
p.publishWants = func(event string, body any, id string) error {
f.events = append(f.events, event)
f.bodies = append(f.bodies, body.(meshwants.Wait))
return nil
}
digest := "sha256:" + strings.Repeat("c", 64)
pl := mma.Assignments{Node: "ace"}
forms := map[string]int{} // by fingerprint: each module's own
modules := []string{}
for _, m := range mods {
modules = append(modules, m.name)
pl.Modules = append(pl.Modules, mma.PlacedModule{Module: m.name})
for _, seat := range m.holds {
scope := "node"
if seat != catalogue.BackupSeat && seat != nodeengine.Seat {
scope = "mesh"
}
pl.Holds = append(pl.Holds, mma.Holding{Claim: seat, Module: m.name, Scope: scope})
}
for fp, form := range m.forms {
forms[fp] = form
}
mdigest := fmt.Sprintf("%064x", len(modules))
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: m.trunk, Manifest: mdigest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath, Src: m.src})
putModuleRaw(p.w, trunkBranch, m.name, mod)
p.w.manifests[mdigest] = parsed{module: m.name, manifest: catalogue.Manifest{Module: m.name}}
endDone(t, p.w, m.name, m.trunk, mdigest)
gkey, _ := grantsstate.PartGrantKey(m.name, m.trunk)
grant, _ := grantsstate.EncodeGrant(grantsstate.Grant{})
p.w.put(buckets.Grants, gkey, grant)
f.runs(m.name, m.run)
wkey, _ := mwc.WantKey("ace", m.name)
old, _ := mwc.EncodeWant(mwc.Want{Fp: m.run, Self: true})
p.w.put(buckets.Wants(), wkey, old)
f.wants.values[wkey] = old
}
composes(t, p.w, "ace", digest)
values, err := mmac.AssignmentsValues(pl)
if err != nil {
t.Fatal(err)
}
for key, raw := range values {
p.w.put(plc.AssignmentsBucket(), key, raw)
}
p.w.heardPresence("ace", false, time.Now()) // ace is online: its last presence event heard is machine-back
objects := memObjects{}
for i, at := range history {
half := meshcatalogclient.Half{Revision: meshcatalog.CatalogRevision{Branch: trunkBranch, Kind: "trunk", Revision: int64(i + 1), Source: int64(i + 1)},
Entries: map[string]meshcatalog.CatalogEntry{}}
for _, module := range modules {
digest := fmt.Sprintf("sha256:%064x", (i+1)*1000+len(half.Entries))
half.Revision.Entries = append(half.Revision.Entries, meshcatalog.EntryRef{Module: module, Digest: digest})
half.Entries[module] = meshcatalog.CatalogEntry{Module: module, Fp: at[module]}
}
placed := mma.Assignments{Node: "ace"}
for _, module := range modules {
placed.Modules = append(placed.Modules, mma.PlacedModule{Module: module})
}
in := assigngraph.Inputs{Halves: map[string]meshcatalogclient.Half{trunkBranch: half}, FirstBranch: func(string) string { return trunkBranch },
Placements: map[string]mma.Assignments{"ace": placed}}
if _, _, err := assigngraph.Keep(ctx, objects, assigngraph.Compute(in), "test", time.Now()); err != nil {
t.Fatal(err)
}
}
p.graph = &graphKeeper{objects: objects}
p.entries = meshcatalogclient.NewEntries(func(_ string, body any) (json.RawMessage, error) {
in := body.(meshcatalog.EntryInput)
entry := meshcatalog.CatalogEntry{Module: "m", Fp: in.Fingerprint, Manifest: map[string]any{"module": "m"}}
if form := forms[in.Fingerprint]; form > 0 {
entry.Manifest = map[string]any{"module": "m", "state": []any{map[string]any{"name": "sessions", "form": form}}}
}
return json.Marshal(meshcatalog.EntryAnswer{Entry: entry})
})
p.entries.Changed = func(meshcatalogclient.EntryRow) { f.answers <- struct{}{} }
return f
}
// runs says module runs fp healthy on ace, heard as the node-engine seat's running and in the have.
func (f *orderFixture) runs(module, fp string) {
have, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: "sha256:" + strings.Repeat("c", 64), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
f.p.w.put(buckets.Have, "ace."+module, have)
f.p.w.running["ace."+module] = nodeengine.Running{Node: "ace", Module: module, Fingerprint: fp}
}
// pass makes a pass, and after it every catalog entry it asked is answered.
func (f *orderFixture) pass() {
f.t.Helper()
f.p.wants(context.Background())
asked := 0
for _, row := range f.p.entries.Rows() {
if row.State == meshcatalogclient.EntryAsked {
asked++
}
}
for range asked {
select {
case <-f.answers:
case <-time.After(10 * time.Second): // a bound on a failure only: the answers come at once
f.t.Fatal("an entry asked was not answered")
}
}
}
// wantAt is the fingerprint module is wanted at on ace.
func (f *orderFixture) wantAt(module string) string {
f.t.Helper()
key, _ := mwc.WantKey("ace", module)
w, err := mwc.DecodeWant(f.wants.values[key])
if err != nil {
f.t.Fatal(err)
}
return w.Fp
}
func (f *orderFixture) waits() []string {
var out []string
for key := range f.p.w.read(buckets.Waits()) {
if acting.IsOrder(key) {
out = append(out, key)
}
}
return out
}
// Design 47 G §298 first edge, A-258, A-259: a module whose kept data's form changes is not moved until the new version of the node-backup
// holder and of the holder of the seat mesh-broker run; the wait is kept under `order.` in the state waits, said as wait-held, and ends
// ran (wait-ended) when the holders run; a module whose kept data keeps its form is moved at once.
func TestAModuleWhoseKeptDataChangesFormWaitsForTheNewBackupHolderAndTheBusModule(t *testing.T) {
f := newOrderFixture(t, []orderMod{
{name: "web", run: orderFP("a"), trunk: orderFP("b"), forms: map[string]int{orderFP("a"): 1, orderFP("b"): 2}},
{name: "plain", run: orderFP("c"), trunk: orderFP("d"), forms: map[string]int{orderFP("c"): 1, orderFP("d"): 1}},
{name: "backup", run: orderFP("e"), trunk: orderFP("f"), holds: []string{catalogue.BackupSeat}},
{name: "bus", run: orderFP("g"), trunk: orderFP("h"), holds: []string{meshbroker.Seat}},
})
f.pass() // the entries are asked: no want crosses a form change unread
if got := f.wantAt("web"); got != orderFP("a") {
t.Fatalf("web is wanted at %s before the entries are read", got)
}
f.pass()
if got := f.wantAt("web"); got != orderFP("a") {
t.Fatalf("web moved across a form change at %s while the new node-backup holder and bus module do not run", got)
}
if got := f.wantAt("plain"); got != orderFP("d") {
t.Errorf("a module whose kept data keeps its form is wanted at %s, not moved", got)
}
if len(f.waits()) != 2 || len(f.events) != 2 || f.events[0] != meshwants.EventWaitHeld || f.bodies[0].Step != seatdef.StepPlace || f.bodies[0].Module != "web" {
t.Fatalf("waits %v events %v bodies %+v: want two wait-held in the step place, `order.ace.web.backup` and `order.ace.web.bus`", f.waits(), f.events, f.bodies)
}
if _, err := acting.Decode(f.p.w.read(buckets.Waits())[acting.OrderKey("ace", "web", "backup")]); err != nil {
t.Fatalf("the wait is not kept under its key: %v", err)
}
f.pass()
if len(f.events) != 2 {
t.Fatalf("a pass that changed nothing said %v", f.events)
}
f.runs("backup", orderFP("f"))
f.pass()
if got := f.wantAt("web"); got != orderFP("a") || len(f.events) != 3 || f.events[2] != meshwants.EventWaitEnded || f.bodies[2].How != acting.HowRan {
t.Fatalf("with the bus module still old: web at %s, events %v", got, f.events)
}
f.runs("bus", orderFP("h"))
f.pass()
f.pass()
if got := f.wantAt("web"); got != orderFP("b") || len(f.waits()) != 0 || len(f.events) != 4 {
t.Fatalf("with both running: web at %s, waits %v, events %v", got, f.waits(), f.events)
}
}
// §298 first edge, the hand: assigner_waits reads an order wait and assigner_release with how `now` lets the module move.
func TestAnOrderWaitIsReadAndReleasedByTheExistingTools(t *testing.T) {
f := newOrderFixture(t, []orderMod{
{name: "web", run: orderFP("a"), trunk: orderFP("b"), forms: map[string]int{orderFP("a"): 1, orderFP("b"): 2}},
{name: "backup", run: orderFP("e"), trunk: orderFP("f"), holds: []string{catalogue.BackupSeat}},
})
f.pass()
f.pass()
var acts []string
s := newPutTools(memStore{waitsState: f.p.kvs[buckets.Waits()].(*memKV), buckets.DeliveryWaitsState: &memKV{values: map[string][]byte{}}, buckets.DeliveredAgainState: &memKV{values: map[string][]byte{}}}, func(key string, body any) (json.RawMessage, error) {
acts = append(acts, key)
return json.RawMessage(`{"ok":true,"log":"logged"}`), nil
})
got, err := s.doWaits(map[string]any{"module": "web"})
if list := got.(map[string]any)["waits"].([]any); err != nil || len(list) != 1 || list[0].(actingSaid).Key != "order.ace.web.backup" {
t.Fatalf("assigner_waits = %+v %v", got, err)
}
if _, err := s.doRelease(map[string]any{"node": "ace", "module": "web", "how": "now", "why": "the restore point is taken by hand"}, "shanks.node-tools"); err != nil || len(acts) == 0 {
t.Fatalf("%v %v", err, acts)
}
f.p.w.put(buckets.Waits(), "order.ace.web.backup", f.p.kvs[buckets.Waits()].(*memKV).values["order.ace.web.backup"])
f.pass()
f.pass()
if got := f.wantAt("web"); got != orderFP("b") || f.bodies[len(f.bodies)-1].How != acting.HowReleased {
t.Fatalf("after the release: web at %s, last %+v", got, f.bodies[len(f.bodies)-1])
}
}
// §298 second edge, A-259: at a revert the node-engine goes back last on its node, after every module that is set back there across a
// form change runs the reverted build.
func TestAtARevertTheNodeEngineGoesBackLast(t *testing.T) {
old, now := map[string]string{"web": orderFP("a"), "engine": orderFP("c")}, map[string]string{"web": orderFP("b"), "engine": orderFP("d")}
f := newOrderFixture(t, []orderMod{
{name: "web", run: orderFP("b"), trunk: orderFP("a"), forms: map[string]int{orderFP("a"): 1, orderFP("b"): 2}},
{name: "engine", run: orderFP("d"), trunk: orderFP("c"), holds: []string{nodeengine.Seat}},
}, old, now)
f.pass()
f.pass()
if f.wantAt("web") != orderFP("a") {
t.Fatalf("web is wanted at %s: the module set back is not held", f.wantAt("web"))
}
if got := f.wantAt("engine"); got != orderFP("d") {
t.Fatalf("the node-engine is set back to %s before web runs its reverted build", got)
}
if w := f.waits(); len(w) != 1 || w[0] != "order.ace.engine.web" || f.bodies[len(f.bodies)-1].Module != "engine" {
t.Fatalf("waits %v bodies %+v", w, f.bodies)
}
f.runs("web", orderFP("a"))
f.pass()
f.pass()
if got := f.wantAt("engine"); got != orderFP("c") || len(f.waits()) != 0 {
t.Fatalf("with web back: the node-engine is wanted at %s, waits %v", got, f.waits())
}
}
// §298 third edge, A-259, A-260: the reverted assigner and gate are wanted only once the indexer's take-in.taken of the trunk branch names a
// source revision at least the trunk's head (the highest src of the trunk's module values).
func TestTheRevertedAssignerAndGateWaitForTheIndexerToTakeInTheTrunksHead(t *testing.T) {
old, now := map[string]string{"asg": orderFP("a"), "gate": orderFP("c"), "idx": orderFP("e")}, map[string]string{"asg": orderFP("b"), "gate": orderFP("d"), "idx": orderFP("f")}
f := newOrderFixture(t, []orderMod{
{name: "asg", run: orderFP("b"), trunk: orderFP("a"), holds: []string{mma.Seat}, src: 6},
{name: "gate", run: orderFP("d"), trunk: orderFP("c"), holds: []string{meshdelivery.Seat}, src: 7},
{name: "idx", run: orderFP("e"), trunk: orderFP("e"), src: 7},
}, old, now)
f.pass()
f.pass()
if f.wantAt("asg") != orderFP("b") || f.wantAt("gate") != orderFP("d") {
t.Fatalf("the reverted assigner (%s) and gate (%s) are wanted before the head is taken in", f.wantAt("asg"), f.wantAt("gate"))
}
if len(f.waits()) != 2 || f.bodies[0].Part != "mesh-delivery-indexer" {
t.Fatalf("waits %v bodies %+v", f.waits(), f.bodies)
}
taken := func(branch string, source int64) {
raw, _ := json.Marshal(meshcatalog.TakeInTaken{Kind: "taken", Key: "m.1", Branch: branch, Source: source})
if err := f.p.w.taken.put(raw); err != nil {
t.Fatal(err)
}
}
taken("beta", 9) // another branch, and
taken(trunkBranch, 6)
f.pass()
if f.wantAt("asg") != orderFP("b") {
t.Fatal("a source revision before the trunk's head was taken in, and the assigner was wanted")
}
taken(trunkBranch, 7)
f.pass()
f.pass()
if f.wantAt("asg") != orderFP("a") || f.wantAt("gate") != orderFP("c") || len(f.waits()) != 0 {
t.Fatalf("after the head is taken in: asg %s gate %s waits %v", f.wantAt("asg"), f.wantAt("gate"), f.waits())
}
}
// A-260: an order wait still held after a restart is said again as wait-held, by a pass that remembers nothing, and ends at the next
// take-in.taken that names the trunk's head.
func TestAnOrderWaitHeldAfterARestartIsSaidAgain(t *testing.T) {
old, now := map[string]string{"asg": orderFP("a")}, map[string]string{"asg": orderFP("b")}
f := newOrderFixture(t, []orderMod{{name: "asg", run: orderFP("b"), trunk: orderFP("a"), holds: []string{mma.Seat}, src: 7}}, old, now)
f.pass()
f.pass()
if len(f.events) != 1 {
t.Fatalf("events %v", f.events)
}
f.p.orderSaid = nil // a process started again
f.pass()
if len(f.events) != 2 || f.events[1] != meshwants.EventWaitHeld || len(f.waits()) != 1 {
t.Fatalf("events %v waits %v", f.events, f.waits())
}
raw, _ := json.Marshal(meshcatalog.TakeInTaken{Kind: "taken", Key: "m.1", Branch: trunkBranch, Source: 8})
if err := f.p.w.taken.put(raw); err != nil {
t.Fatal(err)
}
f.pass()
f.pass()
if f.wantAt("asg") != orderFP("a") || len(f.waits()) != 0 || f.events[len(f.events)-1] != meshwants.EventWaitEnded {
t.Fatalf("asg at %s, waits %v, events %v", f.wantAt("asg"), f.waits(), f.events)
}
}
@@ -76,9 +76,6 @@ type outsideActs struct {
cleared map[string]bool
// sigs is each check's last signature, by node.module.
sigs map[string]string
// own is the machines whose own network is open; ownRead says the read at the start was answered.
own map[string]bool
ownRead bool
// causes is, by condition key, the nodes whose waits stand on it, as the last pass kept them.
causes map[string][]string
// started says the first pass judged every wait again.
@@ -93,7 +90,7 @@ func newOutsideActs(call func(string, any) (json.RawMessage, error), wake func()
settle = outside.DefaultSettle
}
return &outsideActs{call: call, wake: wake, logf: logf, bound: bound, settle: settle, reading: map[string]bool{}, answered: map[string][]outside.Cond{},
dirty: map[string]bool{}, cleared: map[string]bool{}, sigs: map[string]string{}, own: map[string]bool{}, causes: map[string][]string{}}
dirty: map[string]bool{}, cleared: map[string]bool{}, sigs: map[string]string{}, causes: map[string][]string{}}
}
// outsideSettings are the bounds of the wait, the settings outside-wait-minutes and outside-settle-seconds (design 47 G §633, §706),
@@ -135,31 +132,8 @@ func settingFile(path string) (int, error) {
return n, nil
}
// readStart reads the open conditions of every machine once at the start, for the machines whose own network is held.
func (o *outsideActs) readStart() {
go func() {
answer, err := o.call(conditionsVerb, map[string]any{"scope": "machine"})
if err != nil {
o.logf("the open conditions are not read at the start (%v): no machine is held for its own network until its event is heard", err)
return
}
conds, err := outside.ParseConditions(answer)
if err != nil {
o.logf("%v", err)
return
}
o.mu.Lock()
for m := range outside.OwnNetwork(conds) {
o.own[m] = true
}
o.ownRead = true
o.mu.Unlock()
o.wake()
}()
}
// Heard is one of the seat's events condition-raised, -changed or -cleared: it says which machines to judge again and keeps the
// machines whose own network is open; nothing is kept of the condition.
// Heard is one of the seat's events condition-raised, -changed or -cleared: it says which machines to judge again; nothing is kept
// of the condition (the network hold ends, design 47 H §750, H-A-55).
func (o *outsideActs) Heard(subject string, body []byte) {
var e mcseat.ConditionEvent
if err := json.Unmarshal(body, &e); err != nil || e.Key == "" {
@@ -168,9 +142,6 @@ func (o *outsideActs) Heard(subject string, body []byte) {
}
cleared := strings.HasSuffix(subject, "."+mcseat.EventConditionCleared)
o.mu.Lock()
if p := strings.Split(e.Key, "."); len(p) == 3 && p[0] == "machine" && p[2] == "network" {
o.own[p[1]] = !cleared
}
if cleared {
for _, node := range o.causes[e.Key] {
o.dirty[node] = true
@@ -186,16 +157,6 @@ func (o *outsideActs) Heard(subject string, body []byte) {
o.wake()
}
// Held says whether machine's own network is open: no want moves to it.
func (o *outsideActs) Held(machine string) bool {
if o == nil {
return false
}
o.mu.Lock()
defer o.mu.Unlock()
return o.own[machine]
}
// take is the conditions read for machine, consumed (one answer is one judging), or false while the kept call is unanswered,
// which it starts when none is in flight.
func (o *outsideActs) take(machine string) ([]outside.Cond, bool) {
@@ -237,29 +237,12 @@ func TestTheWaitOnAnOutsideCause(t *testing.T) {
})
}
func TestAMachineWhoseOwnNetworkIsOpenGetsNoWant(t *testing.T) {
m := assign.Module{Name: "nats", FP: fpTest, Built: true, Nodes: []string{"ace"}, MachineHeld: func(node string) bool { return node == "ace" }}
ok, rule, why := assign.Holds(m, "ace", assign.Nodes{Online: map[string]bool{"ace": true}})
if ok || rule == 0 || !strings.Contains(why, "machine.ace.network") {
t.Errorf("holds = %v %d %q", ok, rule, why)
}
o := newOutsideActs(nil, func() {}, func(string, ...any) {}, 0, 0)
o.Heard("mesh.seat.mesh-conditions.event.condition-raised", []byte(`{"key":"machine.ace.network","subject":{"id":"ace","scope":"machine","machine":"ace"}}`))
if !o.Held("ace") || o.Held("g14") {
t.Error("the own network condition's event does not hold the machine")
}
o.Heard("mesh.seat.mesh-conditions.event.condition-cleared", []byte(`{"key":"machine.ace.network","subject":{"id":"ace","scope":"machine","machine":"ace"}}`))
if o.Held("ace") {
t.Error("the machine is held after its condition cleared")
}
}
func TestTheToolsReadAndReleaseAnOutsideWait(t *testing.T) {
r := newOutsideRig(t)
r.cond("machine.hub.unreachable", "ace")
r.review(false, nil)
var acts []string
s := newPutTools(memStore{waitsState: &memKV{values: map[string][]byte{}}, buckets.DeliveryWaitsState: &memKV{values: map[string][]byte{}}, buckets.DeliveredAgainState: &memKV{values: map[string][]byte{}}}, func(key string, body any) (json.RawMessage, error) {
s := newPutTools(memStore{waitsState: &memKV{values: map[string][]byte{}}}, func(key string, body any) (json.RawMessage, error) {
acts = append(acts, key)
return json.RawMessage(`{"ok":true,"log":"logged"}`), nil
})
@@ -296,38 +279,4 @@ func TestTheToolsReadAndReleaseAnOutsideWait(t *testing.T) {
if r.bodies[len(r.bodies)-1].How != "go-on" || n.Haves["ace"]["nats"].Health != nodeengineclient.HealthOK {
t.Errorf("last %+v health %s", r.bodies[len(r.bodies)-1], n.Haves["ace"]["nats"].Health)
}
// A-246: a dependent's delivery wait is listed beside them, and released by its module and step delivery, its hand act first.
dw, _ := json.Marshal(deliveryWaiting{Wait: meshwants.Wait{Step: meshwants.WaitStepDelivery, Module: "app", Part: "db", On: "db@1.1.0", Machines: []string{"g14"}}})
s.st.put(buckets.DeliveryWaitsState, "app", dw)
got, err = s.doWaits(map[string]any{"node": "g14"})
if d := got.(map[string]any)["delivery"].([]deliveryWaiting); err != nil || len(d) != 1 || d[0].Module != "app" {
t.Errorf("the delivery waits listed = %+v %v", got, err)
}
if _, err := s.doRelease(map[string]any{"module": "app", "step": "build", "why": "x"}, "shanks.node-tools"); err == nil {
t.Error("a release of another step is taken")
}
if _, err := s.doRelease(map[string]any{"module": "web", "step": "delivery", "why": "x"}, "shanks.node-tools"); err == nil {
t.Error("a release of a module waiting for no delivery is taken")
}
before := len(acts)
if _, err := s.doRelease(map[string]any{"module": "app", "step": "delivery", "why": "db is fine as it runs"}, "shanks.node-tools"); err != nil {
t.Fatal(err)
}
raw, _, _, _ = s.st.get(buckets.DeliveryWaitsState, "app")
var released deliveryWaiting
if json.Unmarshal(raw, &released) != nil || !released.Released || !strings.Contains(released.By, "db is fine") || len(acts) != before+1 {
t.Errorf("the delivery wait after its release = %+v, hand acts %v", released, acts[before:])
}
// A-250: assigner_delivered_again records its hand act, writes the ask and answers asked; assigner_waits lists it.
if _, err := s.doDeliveredAgain(map[string]any{"module": "db", "version": "1.1.0"}, "op"); err == nil {
t.Error("an ask with no why is taken")
}
ans, err := s.doDeliveredAgain(map[string]any{"module": "db", "version": "1.1.0", "why": "the catalog missed it"}, "op")
if err != nil || ans.(map[string]any)["asked"] != "db" || len(acts) != before+2 {
t.Fatalf("assigner_delivered_again = %+v %v", ans, err)
}
got, _ = s.doWaits(map[string]any{})
if a := got.(map[string]any)["delivered-again"].([]againAsk); len(a) != 1 || a[0].Version != "1.1.0" || a[0].By != "op" {
t.Errorf("the asks listed = %+v", a)
}
}
@@ -1,7 +1,6 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"slices"
@@ -10,11 +9,8 @@ import (
"time"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-assigner/internal/acting"
"mesh-delivery-assigner/internal/buckets"
"mesh-delivery-assigner/internal/outside"
)
@@ -37,13 +33,6 @@ type waitSaid struct {
BoundEnds string `json:"bound-ends,omitempty"`
}
// actingSaid is one wait for an acting part's new version as assigner_waits answers it (actingwaits.go).
type actingSaid struct {
Key string `json:"key"`
acting.Wait
BoundEnds string `json:"bound-ends,omitempty"`
}
// doWaits is the tool assigner_waits.
func (s *putTools) doWaits(args map[string]any) (any, error) {
keys, err := s.st.keys(waitsState)
@@ -57,16 +46,6 @@ func (s *putTools) doWaits(args map[string]any) (any, error) {
if err != nil || !found {
continue
}
if acting.Is(key) || acting.IsOrder(key) {
if a, err := acting.Decode(raw); err == nil && (arg(args, "node") == "" || a.Node == arg(args, "node")) && (arg(args, "module") == "" || a.Module == arg(args, "module")) {
said := actingSaid{Key: key, Wait: a}
if d, err := time.ParseDuration(a.Bound); err == nil && !a.Released {
said.BoundEnds = a.ClockFrom.Add(d).UTC().Format("2006-01-02T15:04:05Z")
}
out = append(out, said)
}
continue
}
w, err := outside.Decode(raw)
if err != nil || (arg(args, "node") != "" && w.Node != arg(args, "node")) || (arg(args, "module") != "" && w.Module != arg(args, "module")) {
continue
@@ -79,120 +58,13 @@ func (s *putTools) doWaits(args map[string]any) (any, error) {
}
out = append(out, said)
}
// And each dependent's wait for its dependency's delivery (design 47 G §376, A-246), from the state delivery-waits.
delivery := []deliveryWaiting{}
dkeys, err := s.st.keys(buckets.DeliveryWaitsState)
if err != nil {
return nil, fmt.Errorf("the delivery waits cannot be listed: %w", err)
}
sort.Strings(dkeys)
for _, key := range dkeys {
raw, _, found, err := s.st.get(buckets.DeliveryWaitsState, key)
if err != nil || !found {
continue
}
var w deliveryWaiting
if json.Unmarshal(raw, &w) != nil || (arg(args, "module") != "" && w.Module != arg(args, "module")) ||
(arg(args, "node") != "" && !slices.Contains(w.Machines, arg(args, "node"))) {
continue
}
delivery = append(delivery, w)
}
// And each ask of assigner_delivered_again not yet holding, with why (A-250).
again := []againAsk{}
akeys, err := s.st.keys(buckets.DeliveredAgainState)
if err != nil {
return nil, fmt.Errorf("the asks to say a version delivered again cannot be listed: %w", err)
}
sort.Strings(akeys)
for _, key := range akeys {
raw, _, found, err := s.st.get(buckets.DeliveredAgainState, key)
var a againAsk
if err != nil || !found || json.Unmarshal(raw, &a) != nil || (arg(args, "module") != "" && a.Module != arg(args, "module")) {
continue
}
again = append(again, a)
}
return map[string]any{"waits": out, "delivery": delivery, "delivered-again": again}, nil
}
// toolDeliveredAgain is the tool that asks version-delivered said again for one version (design 47 G §376, A-250).
const toolDeliveredAgain = "assigner_delivered_again"
// doDeliveredAgain is assigner_delivered_again: the hand act is recorded first, then the ask is written into the state
// delivered-again, whose watch the assigner's process hears at once; it answers that it is asked.
func (s *putTools) doDeliveredAgain(args map[string]any, by string) (any, error) {
module, version, why := arg(args, "module"), arg(args, "version"), arg(args, "why")
if module == "" || version == "" || why == "" {
return nil, errors.New("assigner_delivered_again names the module, its version and why: it is kept in the hand-act log")
}
rec := meshhandactsclient.Recorder{Ask: s.ask}
taken, err := rec.Record(meshhandactsclient.Request{What: fmt.Sprintf("assigner_delivered_again %s %s", module, version), Why: why,
Cause: "version-delivered", Verb: "mesh-wants.assigner_delivered_again"})
if err != nil {
return nil, fmt.Errorf("the hand act could not be recorded, so nothing was asked: %w", err)
}
data, err := json.Marshal(againAsk{Module: module, Version: version, By: by, Why: why})
if err != nil {
return nil, err
}
if err := s.st.put(buckets.DeliveredAgainState, keys.EscapeName(module), data); err != nil {
return nil, fmt.Errorf("the ask of %s %s is not written: %w", module, version, err)
}
return map[string]any{"asked": module, "version": version, "hand-act": taken.Log,
"follow": "the assigner says version-delivered again once every present machine placing it runs it healthy; assigner_waits says why it does not yet"}, nil
}
// deliveredAgainTool is assigner_delivered_again as the runtime serves it.
func (s *putTools) deliveredAgainTool() stdio.Tool {
return stdio.Tool{Name: toolDeliveredAgain, Description: "Say version-delivered again for one version of a module, for the operator and the healers " +
"(design 47 G §376): written in the hand-act log first, then asked of the assigner, which says it once every present machine placing " +
"the module runs that version healthy; until then assigner_waits lists the ask with why it does not hold. Answers that it is asked.",
Input: schema(map[string]string{"module": "the module", "version": "its MAJOR.MINOR.PATCH", "why": "why, kept in the hand-act log"},
[]string{"module", "version", "why"}),
Run: func(a map[string]any) (any, error) { return s.doDeliveredAgain(a, stdio.CallerOf(a)) }}
}
// doReleaseDelivery is assigner_release with step delivery: the hand act is recorded first, then the release is written on the
// module's delivery wait, which the assigner's process ends released at its next pass, writing the module's want.
func (s *putTools) doReleaseDelivery(args map[string]any, by string) (any, error) {
module, why := arg(args, "module"), arg(args, "why")
if why == "" {
return nil, errors.New("release says why: it is kept in the hand-act log")
}
key := keys.EscapeName(module)
raw, _, found, err := s.st.get(buckets.DeliveryWaitsState, key)
if err != nil {
return nil, fmt.Errorf("the delivery wait of %s is not read: %w", module, err)
}
var w deliveryWaiting
if !found || json.Unmarshal(raw, &w) != nil || w.Released {
return nil, fmt.Errorf("%s waits for no delivery: assigner_waits lists the delivery waits", module)
}
rec := meshhandactsclient.Recorder{Ask: s.ask}
taken, err := rec.Record(meshhandactsclient.Request{What: fmt.Sprintf("assigner_release %s step delivery (waits on %s)", module, w.On), Why: why,
Cause: "delivery-wait", Verb: "mesh-wants.assigner_release"})
if err != nil {
return nil, fmt.Errorf("the hand act could not be recorded, so nothing was released: %w", err)
}
w.Released, w.By = true, by+": "+why
data, err := json.Marshal(w)
if err != nil {
return nil, err
}
if err := s.st.put(buckets.DeliveryWaitsState, key, data); err != nil {
return nil, fmt.Errorf("the release of %s's delivery wait is not written: %w", module, err)
}
return map[string]any{"released": module, "step": meshwants.WaitStepDelivery, "by": by, "hand-act": taken.Log}, nil
return map[string]any{"waits": out}, nil
}
// doReleaseWait is assigner_release with how: the hand act is recorded first, then the release is written on the wait of node and
// module, which the assigner's process takes at its next pass.
func (s *putTools) doReleaseWait(args map[string]any, by string) (any, error) {
node, module, how, why := arg(args, "node"), arg(args, "module"), arg(args, "how"), arg(args, "why")
if how == acting.HowNow {
return s.doReleaseActing(node, module, why, by)
}
if !slices.Contains([]string{outside.HowGoOn, outside.HowFailed, outside.HowRejudge}, how) {
return nil, fmt.Errorf("how is %s, %s or %s, not %q", outside.HowGoOn, outside.HowFailed, outside.HowRejudge, how)
}
@@ -238,61 +110,9 @@ func (s *putTools) doReleaseWait(args map[string]any, by string) (any, error) {
return map[string]any{"released": key, "how": how, "by": by, "hand-act": taken.Log}, nil
}
// doReleaseActing is assigner_release with how `now`: the entry of module on node moves with its acting parts' running versions. The
// hand act is recorded first; the release is written on each standing wait of the entry, and the process says wait-ended at its next pass.
func (s *putTools) doReleaseActing(node, module, why, by string) (any, error) {
if why == "" {
return nil, errors.New("release says why: it is kept in the hand-act log")
}
keys, err := s.st.keys(waitsState)
if err != nil {
return nil, fmt.Errorf("the waits cannot be listed: %w", err)
}
type one struct {
key string
w acting.Wait
}
var held []one
prefix, orderPrefix := acting.Prefix+node+"."+module+".", acting.OrderPrefix+node+"."+module+"."
for _, k := range keys {
if !strings.HasPrefix(k, prefix) && !strings.HasPrefix(k, orderPrefix) {
continue
}
raw, _, found, err := s.st.get(waitsState, k)
if err != nil || !found {
continue
}
if w, err := acting.Decode(raw); err == nil && !w.Released {
held = append(held, one{k, w})
}
}
if len(held) == 0 {
return nil, fmt.Errorf("%s holds no wait of %s for an acting part: assigner_waits lists them", node, module)
}
rec := meshhandactsclient.Recorder{Ask: s.ask}
taken, err := rec.Record(meshhandactsclient.Request{What: fmt.Sprintf("assigner_release %s %s %s", node, module, acting.HowNow), Why: why,
Cause: "acting-wait", Verb: "mesh-wants.assigner_release"})
if err != nil {
return nil, fmt.Errorf("the hand act could not be recorded, so nothing was released: %w", err)
}
released := []string{}
for _, h := range held {
h.w.Released, h.w.By, h.w.Why = true, by+": "+why, why
data, err := acting.Encode(h.w)
if err != nil {
return nil, err
}
if err := s.st.put(waitsState, h.key, data); err != nil {
return nil, fmt.Errorf("the release of %s on %s is not written: %w", module, node, err)
}
released = append(released, h.key)
}
return map[string]any{"released": released, "how": acting.HowNow, "by": by, "hand-act": taken.Log}, nil
}
// waitsTool is assigner_waits as the runtime serves it.
func (s *putTools) waitsTool() stdio.Tool {
return stdio.Tool{Name: toolWaits, Description: "Every wait of the delivery and where it stands: an entry waiting for an acting part's new version in composing or placing (§266, §268), with its part, version, step, clock-from and bound; and a moved module's failing health check on a " +
return stdio.Tool{Name: toolWaits, Description: "Every wait of the delivery and where it stands: a moved module's failing health check on a " +
"machine whose open conditions name a cause outside the delivery (design 47 G §706), with its module, machine, fingerprint, the " +
"condition's key, what it stands `on`, its clock-from, bound, its ask and its state; a settle shows as settling with its end. Narrowed by " +
"machine or module. Read-only.",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,539 +0,0 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
mdseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assigngraph"
"mesh-delivery-assigner/internal/assignment"
)
// The pins of the assignment graph revisions (design 47 G §153, §178, §216, §579; A-169): the gate says on the seat
// mesh-delivery which revisions a delivery record starts (`pinned`) and stops (`freed`) pointing at, and once at each of its
// starts `pins-stated`. The assigner hears them on its durable consumer of the events stream and keeps, in its old `state`
// section `pins` (4 MiB), one key `trunk.<n>` per assignment graph revision whose value is the list of the records pinning
// it, added or removed by compare-and-set before the event is acknowledged; a record heard twice pins once. Two more keys:
// `made`, written once when the state is first used, and `pins-stated`, the `at` of the last pins-stated applied. A revision
// is removed, its object and its key and the entry objects no kept revision lists and no want or running build names
// (§179), when its list is empty and it is not current (the newest the assigner wrote), only while the consumer is caught up
// and once a pins-stated said after `made` was applied; judged on a freed, on a revision ceasing to be current, on being
// caught up, and at start once both hold. Never on a timer, and never by reading the gate's state.
const (
pinsState = "pins"
pinsTool = "assigner_pins"
unpinTool = "assigner_unpin"
pinsMadeKey = "made"
pinsStatedKey = "pins-stated"
pinsCapBytes = 4 << 20
pinMissingKind = "pin-missing"
)
// PinsValue is one value of the state pins: the records that pin the revision, and whether the revision was no longer held
// when a record pinned it.
type PinsValue struct {
Records []string `json:"records"`
Missing bool `json:"missing,omitempty"`
}
// pinKey is the key of an assignment graph revision, its object's own name (A-169).
func pinKey(revision int64) string { return assigngraph.TrunkObject(revision) }
// pinRevision is the revision a key of the state names, and whether it names one.
func pinRevision(key string) (int64, bool) {
n, ok := strings.CutPrefix(key, "trunk.")
if !ok {
return 0, false
}
r, err := strconv.ParseInt(n, 10, 64)
return r, err == nil && r > 0
}
// pinObjects is the object bucket of the revisions as the pins remove from it.
type pinObjects interface {
assigngraph.Objects
Delete(ctx context.Context, name string) error
}
// pinKeeper keeps the pins and removes what nothing pins.
type pinKeeper struct {
ctx context.Context
st endStore
objects pinObjects
// inUse says a want or a running build names the module's fingerprint (§179).
inUse func(module, fp string) bool
findings assign.Findings
now func() time.Time
logf func(string, ...any)
mu sync.Mutex
// caught is whether the last event applied left none of the consumer's messages pending.
caught bool
}
// edit applies change to the value at key by compare-and-set, again while another write comes between.
func (k *pinKeeper) edit(key string, change func(v PinsValue, found bool) (PinsValue, bool)) error {
for {
raw, rev, err := k.st.get(key)
if err != nil {
return err
}
var v PinsValue
if raw != nil {
if err := json.Unmarshal(raw, &v); err != nil {
return fmt.Errorf("the pins of %s do not read: %w", key, err)
}
}
next, write := change(v, raw != nil)
if !write {
return nil
}
value, _ := json.Marshal(next)
if err := k.st.swap(key, value, rev); errors.Is(err, errSwapped) {
continue
} else {
return err
}
}
}
// held says the revision's object is kept.
func (k *pinKeeper) held(revision int64) (bool, error) {
_, err := k.objects.Get(k.ctx, assigngraph.TrunkObject(revision))
if errors.Is(err, assigngraph.ErrNoObject) {
return false, nil
}
return err == nil, err
}
// pin adds record to each assignment graph revision of p; a revision no longer held is written missing, with the finding
// pin-missing naming the record.
func (k *pinKeeper) pin(p mdseat.Pins) error {
for _, r := range p.Assignment {
held, err := k.held(r)
if err != nil {
return err
}
err = k.edit(pinKey(r), func(v PinsValue, _ bool) (PinsValue, bool) {
if slices.Contains(v.Records, p.Record) && (held || v.Missing) {
return v, false
}
if !slices.Contains(v.Records, p.Record) {
v.Records = append(v.Records, p.Record)
slices.Sort(v.Records)
}
v.Missing = v.Missing || !held
return v, true
})
if err != nil {
return err
}
if !held {
k.missing(r, p.Record)
}
}
return nil
}
// free removes record from each assignment graph revision of p; a freed applied twice changes nothing.
func (k *pinKeeper) free(p mdseat.Pins) error {
for _, r := range p.Assignment {
err := k.edit(pinKey(r), func(v PinsValue, found bool) (PinsValue, bool) {
i := slices.Index(v.Records, p.Record)
if !found || i < 0 {
return v, false
}
v.Records = slices.Delete(v.Records, i, i+1)
return v, true
})
if err != nil {
return err
}
}
return nil
}
// missing writes the finding pin-missing, scope the assigner, id the revision.
func (k *pinKeeper) missing(revision int64, record string) {
if k.findings.Put == nil {
k.logf("the revision %d the record %s pins is not held, and no finding writer is wired to say so", revision, record)
return
}
o := assign.Observed{Scope: assignment.Module(), ID: strconv.FormatInt(revision, 10), Kind: pinMissingKind,
Summary: fmt.Sprintf("the delivery record %s pins the assignment graph revision %d, which the assigner no longer holds", record, revision),
Headline: "A delivery record pins a revision the assigner no longer holds",
Explanation: fmt.Sprintf("The record %s pinned revision %d after it was removed; %s clears it.", record, revision, unpinTool),
Source: assignment.Module()}
if err := k.findings.Put(o.Finding(k.now())); err != nil {
k.logf("the finding %s of revision %d is not written: %v", pinMissingKind, revision, err)
}
}
// made writes the key made once, create-only; one there already stays.
func (k *pinKeeper) made() error {
raw, _, err := k.st.get(pinsMadeKey)
if err != nil || raw != nil {
return err
}
value, _ := json.Marshal(k.now().UTC())
if err := k.st.swap(pinsMadeKey, value, 0); err != nil && !errors.Is(err, errSwapped) {
return err
}
return nil
}
// timeAt is the time a key holds; false when it holds none.
func (k *pinKeeper) timeAt(key string) (time.Time, bool, error) {
raw, _, err := k.st.get(key)
if err != nil || raw == nil {
return time.Time{}, false, err
}
var t time.Time
if err := json.Unmarshal(raw, &t); err != nil {
return t, false, fmt.Errorf("the key %s does not read: %w", key, err)
}
return t, true, nil
}
// stated keeps the at of a pins-stated applied.
func (k *pinKeeper) stated(at time.Time) error {
for {
raw, rev, err := k.st.get(pinsStatedKey)
if err != nil {
return err
}
var was time.Time
if raw != nil && json.Unmarshal(raw, &was) == nil && !at.After(was) {
return nil
}
value, _ := json.Marshal(at.UTC())
if err := k.st.swap(pinsStatedKey, value, rev); errors.Is(err, errSwapped) {
continue
} else {
return err
}
}
}
// statedSinceMade says a pins-stated said after the state was made was applied.
func (k *pinKeeper) statedSinceMade() (bool, error) {
made, ok, err := k.timeAt(pinsMadeKey)
if err != nil || !ok {
return false, err
}
at, ok, err := k.timeAt(pinsStatedKey)
if err != nil || !ok {
return false, err
}
return at.After(made), nil
}
// hear applies one of the seat mesh-delivery's events and acknowledges it only once applied.
func (k *pinKeeper) hear(m jetstream.Msg) {
err := k.apply(m.Subject(), m.Data())
if err != nil {
k.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
_ = m.Ack()
caught := false
if meta, merr := m.Metadata(); merr == nil {
caught = meta.NumPending == 0
}
k.mu.Lock()
was := k.caught
k.caught = caught
k.mu.Unlock()
if caught && (!was || m.Subject() != mdseat.SubjectPinned) {
k.judge() // on a freed, on a candidate's heads replaced, on pins-stated, and on being caught up
}
}
// apply takes one event's body.
func (k *pinKeeper) apply(subject string, data []byte) error {
switch subject {
case mdseat.SubjectPinned, mdseat.SubjectFreed:
var p mdseat.Pins
if err := json.Unmarshal(data, &p); err != nil || p.Record == "" {
k.logf("%s holds no pins naming a record, and is not taken: %v", subject, err)
return nil
}
if subject == mdseat.SubjectPinned {
return k.pin(p)
}
return k.free(p)
case mdseat.SubjectPinsStated:
var s mdseat.PinsStatedEvent
if err := json.Unmarshal(data, &s); err != nil || s.At.IsZero() {
k.logf("%s holds no at, and is not taken: %v", subject, err)
return nil
}
return k.stated(s.At)
}
return nil // heads-replaced: a candidate's revision stops being current, judged after
}
// judge removes every revision neither pinned nor current, when the rule allows a removal at all.
func (k *pinKeeper) judge() {
k.mu.Lock()
caught := k.caught
k.mu.Unlock()
if !caught {
return
}
ok, err := k.statedSinceMade()
if err != nil {
k.logf("the pins are not judged: %v", err)
return
}
if !ok {
return // no pins-stated applied since the state was made: a pin said before may not be heard yet
}
if err := k.remove(); err != nil {
k.logf("the revisions nothing pins are not removed: %v", err)
}
}
// remove removes each kept revision that is not current and that no record pins, and then the entries left unlisted.
func (k *pinKeeper) remove() error {
names, err := k.objects.Names(k.ctx)
if err != nil {
return err
}
var kept []int64
for _, n := range names {
if r, ok := pinRevision(n); ok {
kept = append(kept, r)
}
}
if len(kept) == 0 {
return nil
}
current := slices.Max(kept)
listed := map[string]bool{}
removed := 0
for _, r := range kept {
raw, _, err := k.st.get(pinKey(r))
if err != nil {
return err
}
var v PinsValue
if raw != nil {
if err := json.Unmarshal(raw, &v); err != nil {
return fmt.Errorf("the pins of %d do not read: %w", r, err)
}
}
if r == current || len(v.Records) > 0 {
rev, err := assigngraph.ReadRevision(k.ctx, k.objects, r)
if err != nil {
return err
}
for _, e := range rev.Entries {
listed[e.Digest] = true
}
continue
}
if err := k.objects.Delete(k.ctx, assigngraph.TrunkObject(r)); err != nil {
return fmt.Errorf("revision %d: %w", r, err)
}
if raw != nil {
if err := k.st.drop(pinKey(r)); err != nil {
return fmt.Errorf("the pins of %d: %w", r, err)
}
}
removed++
}
if removed == 0 {
return nil
}
// A run's candidate kept now lists its entries too, until its group-ended drops it (A-201, A-235).
for _, n := range names {
group, heads, ok := meshwants.ParseAssignmentRevisionsByCandidateGroupHeadsKey(n)
if !ok {
continue
}
rev, err := assigngraph.ReadCandidate(k.ctx, k.objects, group, heads)
if err != nil {
return err
}
for _, e := range rev.Entries {
listed[e.Digest] = true
}
}
for _, n := range names {
digest, ok := strings.CutPrefix(n, "entry.")
if !ok || listed[digest] {
continue
}
e, err := assigngraph.ReadEntry(k.ctx, k.objects, digest)
if err != nil {
return err
}
if k.inUse != nil && k.inUse(e.Module, e.Fp) {
continue
}
if err := k.objects.Delete(k.ctx, n); err != nil {
return fmt.Errorf("the entry %s: %w", digest, err)
}
}
k.logf("%d assignment graph revisions no record pins and not current are removed", removed)
return nil
}
// hearPins registers the seat mesh-delivery's four events on the assigner's hub.
func hearPins(hub *process.EventHub, k *pinKeeper) error {
for _, s := range []string{mdseat.SubjectPinned, mdseat.SubjectFreed, mdseat.SubjectHeadsReplaced, mdseat.SubjectPinsStated} {
if err := hub.Handle(s, k.hear); err != nil {
return fmt.Errorf("%s: %w", s, err)
}
}
return nil
}
// pinsTools are assigner_pins and assigner_unpin over the runtime's states.
func pinsTools(st store, ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
return []stdio.Tool{{Name: pinsTool, Description: "the assignment graph revisions the delivery records pin (design 47 G §579): per revision " +
"the records that pin it and whether it was missing when pinned, the newest revision kept (current, never removed), when the state " +
"was made, the last pins-stated applied, and the state's fill against its cap of 4 MiB.",
Run: func(map[string]any) (any, error) { return readPins(st) }},
{Name: unpinTool, Description: "Remove one record from a revision's pins, for a freed that was lost (design 47 G §579); written in the " +
"hand-act log first. The removal rule then applies.",
Input: schema(map[string]string{"revision": "the assignment graph revision's number", "record": "the delivery record's id",
"why": "why it is removed by hand"}, []string{"revision", "record", "why"}),
Run: func(a map[string]any) (any, error) {
record, _ := a["record"].(string)
why, _ := a["why"].(string)
return unpin(st, ask, fmt.Sprint(a["revision"]), record, why, stdio.CallerOf(a))
}}}
}
// readPins is what assigner_pins answers.
func readPins(st store) (any, error) {
ks, err := st.keys(pinsState)
if err != nil {
return nil, err
}
sort.Strings(ks)
revisions := map[string]PinsValue{}
out := map[string]any{"revisions": revisions}
var newest int64
bytes := 0
for _, key := range ks {
raw, _, found, err := st.get(pinsState, key)
if err != nil || !found {
continue
}
bytes += len(key) + len(raw)
if r, ok := pinRevision(key); ok {
var v PinsValue
if json.Unmarshal(raw, &v) == nil {
revisions[key] = v
}
newest = max(newest, r)
continue
}
out[key] = json.RawMessage(raw)
}
out["fill"] = meshwants.Fill{Store: pinsState, Bytes: int64(bytes), Cap: pinsCapBytes}
if newest > 0 {
out["newest-pinned"] = newest
}
return out, nil
}
// unpin removes one record from one revision's list, the hand act recorded first.
func unpin(st store, ask func(string, any) (json.RawMessage, error), revision, record, why, by string) (any, error) {
r, err := strconv.ParseInt(strings.TrimPrefix(revision, "trunk."), 10, 64)
switch {
case err != nil || r <= 0:
return nil, fmt.Errorf("revision %q is no assignment graph revision's number", revision)
case record == "" || why == "":
return nil, errors.New("name the record and say why")
case by == "" || by == stdio.Unproven:
return nil, errors.New("an unpin names who asks it, and the runtime proved no caller")
}
key := pinKey(r)
raw, _, found, err := st.get(pinsState, key)
if err != nil {
return nil, err
}
var v PinsValue
if found {
if err := json.Unmarshal(raw, &v); err != nil {
return nil, err
}
}
i := slices.Index(v.Records, record)
if i < 0 {
return nil, fmt.Errorf("the record %s does not pin revision %d: %s lists its pins", record, r, pinsTool)
}
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: unpinTool + " " + key + " " + record,
Why: why + " (" + by + ")", Cause: "unpin"})
if err != nil {
return nil, fmt.Errorf("the hand act is not recorded, so nothing is removed: %w", err)
}
v.Records = slices.Delete(v.Records, i, i+1)
value, _ := json.Marshal(v)
if err := st.put(pinsState, key, value); err != nil {
return nil, err
}
return map[string]any{"revision": r, "unpinned": record, "records": v.Records, "hand-act": taken.Log}, nil
}
// watchUnpins judges again when a revision's pins change in the state itself, as assigner_unpin writes them from the tool
// process: the assigner's own state, heard as it changes, never on a timer.
func (k *pinKeeper) watchUnpins(kv jetstream.KeyValue) {
w, err := kv.WatchAll(k.ctx, jetstream.UpdatesOnly())
if err != nil {
k.logf("the state %s is not watched, so a hand unpin is judged at the next freed or revision: %v", pinsState, err)
return
}
go func() {
defer func() { _ = w.Stop() }()
for e := range w.Updates() {
if e == nil {
continue
}
if _, ok := pinRevision(e.Key()); ok && e.Operation() == jetstream.KeyValuePut {
k.judge()
}
}
}()
}
// inUseOf says a want or a running build names the module's fingerprint, as the world holds them now.
func inUseOf(w *world) func(module, fp string) bool {
return func(module, fp string) bool {
for _, want := range w.wantsOf()[module] {
if want.Fp == fp {
return true
}
}
for _, mods := range w.runningNow() {
if r, ok := mods[module]; ok && r.Fingerprint == fp {
return true
}
}
return false
}
}
func pinsBucket() string { return assignment.Module() + "_" + pinsState }
@@ -1,119 +0,0 @@
package main
import (
"context"
"encoding/json"
"testing"
"time"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
mdseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assigngraph"
)
func (m memObjects) Delete(_ context.Context, name string) error { delete(m, name); return nil }
// The pins of the assignment graph revisions (design 47 G §153, §178, §579; A-169): a revision two records pin stays until
// both free it; a record pinning twice pins once; the current revision is never removed; nothing is removed before a
// pins-stated said after the state was made, nor while the consumer is behind; a revision no longer held is pinned missing,
// with the finding pin-missing; an entry another kept revision lists, or a want or a running build names, stays.
func TestPinsKeepARevisionWhileARecordPinsIt(t *testing.T) {
objects := memObjects{}
entry := func(module, fp string) string {
e := meshwants.AssignmentEntry{Node: "n1", Module: module, Fp: fp}
d := assigngraph.EntryDigest(e)
raw, _ := json.Marshal(e)
objects[assigngraph.EntryObject(d)] = raw
return d
}
shared, old, running := entry("a", "fp-a"), entry("b", "fp-b1"), entry("c", "fp-c1")
revision := func(n int64, digests ...string) {
rev := meshwants.AssignmentRevision{Revision: n}
for _, d := range digests {
rev.Entries = append(rev.Entries, meshwants.NodeEntryRef{Node: "n1", Digest: d})
}
raw, _ := json.Marshal(rev)
objects[assigngraph.TrunkObject(n)] = raw
}
// A run's candidate lists an entry no trunk revision lists (A-201): it stays while the candidate is kept.
cand := entry("d", "fp-d2")
candRaw, _ := json.Marshal(meshwants.AssignmentRevision{Revision: 1, Kind: "candidate", Group: "run-7", Heads: "h1",
Entries: []meshwants.NodeEntryRef{{Node: "n1", Module: "d", Digest: cand}}})
objects[assigngraph.CandidateObject("run-7", "h1")] = candRaw
revision(1, shared, old, running)
revision(2, shared, old)
revision(3, shared)
var found []mcseat.Finding
clock := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
k := &pinKeeper{ctx: context.Background(), st: newMemEnds(), objects: objects, now: func() time.Time { return clock },
logf: t.Logf,
inUse: func(module, fp string) bool { return module == "c" && fp == "fp-c1" },
findings: assign.Findings{Put: func(f mcseat.Finding) error { found = append(found, f); return nil }}}
if err := k.made(); err != nil {
t.Fatal(err)
}
say := func(subject string, body any) {
t.Helper()
raw, _ := json.Marshal(body)
if err := k.apply(subject, raw); err != nil {
t.Fatal(err)
}
k.judge()
}
pins := func(record string, revs ...int64) mdseat.Pins { return mdseat.Pins{Record: record, Assignment: revs} }
has := func(n int64) bool { _, ok := objects[assigngraph.TrunkObject(n)]; return ok }
k.caught = true
say(mdseat.SubjectPinned, pins("r1", 1))
say(mdseat.SubjectPinned, pins("r1", 1))
say(mdseat.SubjectPinned, pins("r2", 1))
say(mdseat.SubjectFreed, pins("r9", 2)) // nothing pins 2, but no pins-stated since made: nothing removed
if !has(2) {
t.Fatal("revision 2 was removed before a pins-stated said after the state was made")
}
k.caught = false
say(mdseat.SubjectPinsStated, mdseat.PinsStatedEvent{At: clock.Add(time.Minute)})
if !has(2) {
t.Fatal("revision 2 was removed while the consumer was behind")
}
k.caught = true
say(mdseat.SubjectFreed, pins("r1", 1))
if has(2) {
t.Error("revision 2, neither pinned nor current, is kept")
}
if !has(1) || !has(3) {
t.Error("revision 1 (pinned by r2) or 3 (current) was removed")
}
raw, _, _ := k.st.get(pinKey(1))
if string(raw) != `{"records":["r2"]}` {
t.Errorf("the pins of 1 = %s, want r2 alone (r1 pinned twice pins once, and freed once)", raw)
}
say(mdseat.SubjectFreed, pins("r2", 1))
if has(1) {
t.Error("revision 1 is kept once both records freed it")
}
if _, ok := objects[assigngraph.EntryObject(old)]; ok {
t.Error("the entry no kept revision lists and nothing names is kept")
}
if _, ok := objects[assigngraph.EntryObject(running)]; !ok {
t.Error("the entry of a running build is removed")
}
if _, ok := objects[assigngraph.EntryObject(shared)]; !ok {
t.Error("the entry the current revision lists is removed")
}
if _, ok := objects[assigngraph.EntryObject(cand)]; !ok {
t.Error("the entry a run's kept candidate lists is removed")
}
say(mdseat.SubjectHeadsReplaced, mdseat.HeadsReplacedEvent{})
if _, ok := objects[assigngraph.CandidateObject("run-7", "h1")]; !ok {
t.Error("the gate's heads-replaced dropped a run's candidate")
}
say(mdseat.SubjectPinned, pins("r3", 2))
raw, _, _ = k.st.get(pinKey(2))
if string(raw) != `{"records":["r3"],"missing":true}` || len(found) != 1 || found[0].Kind != pinMissingKind || found[0].ID != "2" {
t.Errorf("a pin of a revision no longer held = %s, findings %+v", raw, found)
}
}
@@ -16,18 +16,20 @@ import (
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
mprc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient"
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
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"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-assigner/internal/assign"
)
// The wants follow a passed pipeline (design 47 G §29, §35, §325, §352): the runner says each pipeline's end as
// pipeline-ended, and a group's as group-ended. The assigner keeps, in its old state `written`, one key per module and
// watched branch: the source revision and end count of the newest end it heard for it, and whether the wants were written
// from it. A newer end replaces it by compare-and-set; an older one, or the same one again, writes nothing.
// The wants follow a passed pipeline (design 47 H §750): the runner says each pipeline's end once, per source revision, as
// pipeline-ended on `pipeline-ended.<branch>.<source>`, naming per mover its fingerprint, its released version and its tier
// (§746). The assigner keeps, in its state `written` (G §352), one key per module and watched branch: the newest released
// version of the module on that branch whose pipeline passed, with the pipeline and the mover's rank in it. A newer version
// replaces it by compare-and-set; an older one, the same one again, a failed pipeline and a run on request write nothing.
// writtenState is the assigner's state of the pipeline ends its wants follow; writtenTool reads it.
const (
@@ -35,23 +37,17 @@ const (
writtenTool = "assigner_written"
)
// pipelineEndedSubject and groupEndedSubject are the runner's events the assigner consumes.
const (
pipelineEndedSubject = "mesh.seat." + mpr.Seat + ".event." + mpr.EventPipelineEnded + ".>"
groupEndedSubject = "mesh.seat." + mpr.Seat + ".event." + mpr.EventGroupEnded + ".>"
)
// pipelineEndedSubject is the runner's event the assigner consumes.
const pipelineEndedSubject = "mesh.seat." + mpr.Seat + ".event." + mpr.EventPipelineEnded + ".>"
// End is one value of the state written: the newest end of a module's pipeline on a watched branch.
// End is one value of the state written: the newest version of a module released on a watched branch whose pipeline passed.
type End struct {
Pipeline string `json:"pipeline"`
Source int64 `json:"source"`
EndCount int64 `json:"end-count"`
Fp string `json:"fp"`
Commit string `json:"commit,omitempty"`
// Passed: the pipeline ended passed, every required step passed (and, for a group, the group ended passed).
Passed bool `json:"passed"`
// Written: the wants were written from this end.
Written bool `json:"written,omitempty"`
Why string `json:"why,omitempty"`
Version string `json:"version"`
// Rank is the mover's tier in the pipeline's delivery order, from 1 (§746, §750).
Rank int64 `json:"rank"`
}
// endKey is the key of a module on a watched branch, each name escaped as a key's name is.
@@ -59,15 +55,10 @@ func endKey(module, branch string) string {
return keys.EscapeName(module) + "." + keys.EscapeName(branch)
}
// newer says whether an end of (source, count) replaces the one kept: a later source revision, or the same one ended again.
func (e End) newer(source, count int64) bool {
return source > e.Source || (source == e.Source && count > e.EndCount)
}
// requiredPassed says whether no required step of a pipeline stands failed, unasked or unended (design 47 G §30: a failed
// optional step holds nothing).
func requiredPassed(p mpr.PipelineEnded) bool {
for _, s := range p.Steps {
// moverPassed says whether no required step of a mover stands failed, unasked or unended: a required step ending "nothing to
// run" counts as passed, as a bypassed one does (design 47 H §746, H-A-3); a failed optional step holds nothing (G §30).
func moverPassed(m mpr.MoverEnded) bool {
for _, s := range m.Steps {
if s.Status != mpr.StepResultStatusRequired {
continue
}
@@ -78,7 +69,7 @@ func requiredPassed(p mpr.PipelineEnded) bool {
return false
}
}
return p.Outcome == mpr.PipelineEndedOutcomePassed
return true
}
// endStore is the kept state written: the bus bucket, or a test's.
@@ -139,19 +130,19 @@ func isWrongSequence(err error) bool {
return errors.As(err, &ae) && ae.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequence
}
// pipelineEnds follows the runner's ends. A nil *pipelineEnds is the trunk-only want, kept until the first registrations
// (design 47 G §95, §353).
// pipelineEnds follows the runner's ends; a nil *pipelineEnds keeps none, and no want is written from it.
type pipelineEnds struct {
st endStore
wake func()
logf func(string, ...any)
// on is whether the wants follow the ends: set by the first registration heard, never before (design 47 G §95, §353).
// on says the first registration was heard (design 47 G §353), said once in the journal.
on atomic.Bool
mu sync.Mutex
// firsts is, by module, the first watched branch of its registration, the branch of a placement that names none (design
// 47 G §14).
firsts map[string]string
// runEnded is told a run on request's group-ended, its group `run-<id>`, to drop the run's candidate (A-235); nil drops nothing.
// 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.
runEnded func(group string) error
// left is told the key of a pipeline ended superseded or cancelled, whose composition steps leave the runs they read
// (design 47 G §723, A-469n); none tells nothing. Set once the composition steps are served, after the hub starts.
@@ -160,110 +151,131 @@ type pipelineEnds struct {
onBranches func([]string)
// trunk names the first watched branch, the trunk's (design 47 G §507), the branch of a module registered with none.
trunk func() string
// runner is the module holding the seat mesh-pipeline-runner, as the last pass read it from the acting edges (A-334); nil
// until a pass read the graph.
runner atomic.Pointer[string]
// held are the group members' pipeline-ended heard before a pass read the graph, by their body: unacknowledged, so the
// bus keeps them, and taken once the runner is read (A-334), never dropped for the runner not being known yet.
held map[string]jetstream.Msg
}
// setRunner keeps the module holding the seat mesh-pipeline-runner, read by the pass from the acting edges (A-334); the
// first one takes the group members' ends held until the graph was read.
func (e *pipelineEnds) setRunner(module string) {
e.mu.Lock()
first := e.runner.Swap(&module) == nil
held := e.held
e.held = nil
e.mu.Unlock()
if !first {
return
}
for _, m := range held {
e.hearPipeline(m)
}
}
// holdUntilRead keeps m, a group member's pipeline-ended, until a pass reads the runner from the graph; false when the
// runner is read already, so m is taken now.
func (e *pipelineEnds) holdUntilRead(m jetstream.Msg) bool {
e.mu.Lock()
defer e.mu.Unlock()
if e.runner.Load() != nil {
return false
}
if e.held == nil {
e.held = map[string]jetstream.Msg{}
}
e.held[string(m.Data())] = m
e.logf("%s is a group member's end heard before the assignment graph is read: held until a pass reads which module is the runner (A-334)", m.Subject())
return true
}
// isRunner says whether module holds the seat mesh-pipeline-runner, as the last pass read it.
func (e *pipelineEnds) isRunner(module string) bool {
r := e.runner.Load()
return r != nil && *r != "" && *r == module
// now is the clock of the tier progress (tiers.go); nil is time.Now.
now func() time.Time
}
func newPipelineEnds(st endStore, wake func(), logf func(string, ...any)) *pipelineEnds {
return &pipelineEnds{st: st, wake: wake, logf: logf, firsts: map[string]string{}}
}
// take keeps one pipeline's end if it is newer than the one kept for its module and branch, by compare-and-set.
func (e *pipelineEnds) take(p mpr.PipelineEnded, passed bool) error {
key := endKey(p.Module, p.Branch)
for {
raw, rev, err := e.st.get(key)
if err != nil {
return err
// 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
// nothing. It says whether any key changed.
func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
if p.Outcome != mpr.PipelineEndedOutcomePassed || p.Run != "" {
return false, nil
}
changed := false
var kept []tierMover
defer func() {
if err := e.startTiers(p.Pipeline, kept); err != nil {
e.logf("the tier progress of %s is not written: %v", p.Pipeline, err)
}
if raw != nil {
var kept End
if err := json.Unmarshal(raw, &kept); err == nil && !kept.newer(p.Source, p.EndCount) {
return nil // an older end, or this one again
}()
for _, m := range p.Movers {
if m.Version == "" || m.Fingerprint == "" || !moverPassed(m) {
continue
}
key := endKey(m.Module, p.Branch)
for {
raw, rev, err := e.st.get(key)
if err != nil {
return changed, err
}
if raw != nil {
var kept End
if err := json.Unmarshal(raw, &kept); err == nil && compareVersion(m.Version, kept.Version) <= 0 {
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)})
if err != nil {
return changed, err
}
if err := e.st.swap(key, value, rev); errors.Is(err, errSwapped) {
continue
} else if err != nil {
return changed, err
}
changed = true
kept = append(kept, tierMover{Module: m.Module, Fp: m.Fingerprint, Tier: max(m.Tier, 1)})
break
}
end := End{Source: p.Source, EndCount: p.EndCount, Fp: p.Fingerprint, Commit: p.Commit, Passed: passed, Why: p.Why}
value, err := json.Marshal(end)
if err != nil {
return err
}
if err := e.st.swap(key, value, rev); errors.Is(err, errSwapped) {
continue
} else if err != nil {
return err
}
e.wake()
return nil
}
return changed, nil
}
// markWritten says the wants of module on branch were written from the end it keeps, if that is still the end of fp.
func (e *pipelineEnds) markWritten(module, branch, fp string) {
key := endKey(module, branch)
for {
raw, rev, err := e.st.get(key)
var kept End
if err != nil || raw == nil || json.Unmarshal(raw, &kept) != nil || kept.Fp != fp || kept.Written {
return
}
kept.Written = true
value, _ := json.Marshal(kept)
if err := e.st.swap(key, value, rev); errors.Is(err, errSwapped) {
continue
} else if err != nil {
e.logf("the end of %s on %s is not marked written: %v", module, branch, err)
}
return
// 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) {
if e == nil {
return End{}, false
}
}
// passedAt says whether the newest end kept for module on branch passed at fp.
func (e *pipelineEnds) passedAt(module, branch, fp string) bool {
raw, _, err := e.st.get(endKey(module, branch))
var kept End
return err == nil && raw != nil && json.Unmarshal(raw, &kept) == nil && kept.Passed && kept.Fp == fp
if err != nil || raw == nil || json.Unmarshal(raw, &kept) != nil || kept.Fp == "" {
return End{}, false
}
return kept, true
}
// target is the build module's wants on branch name (design 47 H §750): the newest version released there whose pipeline
// passed, with the pipeline and the mover's rank; false when none is kept, or its pipeline's tier progress has not reached its
// rank (§751).
func (e *pipelineEnds) target(module, branch string) (assign.Target, bool) {
end, ok := e.endOf(module, e.branchOf(module, branch))
if !ok || !e.tierWritten(end) {
return assign.Target{}, false
}
return assign.Target{Fp: end.Fp, Version: end.Version, Pipeline: end.Pipeline, Rank: end.Rank}, true
}
// hearPipeline takes a pipeline-ended: a passed one's released versions are kept (take), and a run on request's drops the
// run's candidate assignment graph (A-235, H-A-58); a run delivers nothing (design 47 G §29, §64). A pipeline ended superseded or
// cancelled has its composition steps leave the runs they read (G §723).
func (e *pipelineEnds) hearPipeline(m jetstream.Msg) {
p, err := mprc.PipelineEnded(m.Data())
if err != nil {
e.logf("%s is not taken: %v", m.Subject(), err)
_ = m.Ack()
return
}
if left := e.left.Load(); left != nil && (p.Outcome == mpr.PipelineEndedOutcomeSuperseded || p.Outcome == mpr.PipelineEndedOutcomeCancelled) {
if err := (*left)(p.Pipeline); err != nil {
e.logf("%s: the composition steps of %s do not all leave their runs: %v; it is heard again", m.Subject(), p.Pipeline, err)
_ = m.Nak()
return
}
}
if p.Run != "" {
if e.runEnded != nil {
if err := e.runEnded(runGroupPrefix + p.Run); err != nil {
e.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
}
_ = m.Ack()
return
}
changed, err := e.take(p)
if err != nil {
e.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
if changed {
e.wake()
}
_ = m.Ack()
}
// hearEnds registers pipeline-ended on the assigner's hub.
func hearEnds(hub *process.EventHub, e *pipelineEnds) error {
if err := hub.Handle(pipelineEndedSubject, e.hearPipeline); err != nil {
return fmt.Errorf("%s: %w", pipelineEndedSubject, err)
}
return nil
}
// branchOf is the watched branch a placement names, else the first of the module's registration, else the trunk's.
@@ -282,79 +294,9 @@ func (e *pipelineEnds) branchOf(module, placed string) string {
return ""
}
// hearPipeline takes a pipeline-ended. A pipeline of a group writes nothing on its own end, but the runner's: in a group
// take-in that changes the runner it is the acting part the other members wait on, so it goes first, wanted on its own end
// once that passed, ahead of the group (A-334, as the node-engine does, §268). A run on request delivers nothing (design 47 G
// §29, §64).
func (e *pipelineEnds) hearPipeline(m jetstream.Msg) {
p, err := mprc.PipelineEnded(m.Data())
if left := e.left.Load(); err == nil && left != nil && (p.Outcome == mpr.PipelineEndedOutcomeSuperseded || p.Outcome == mpr.PipelineEndedOutcomeCancelled) {
if err := (*left)(p.Pipeline); err != nil {
e.logf("%s: the composition steps of %s do not all leave their runs: %v; it is heard again", m.Subject(), p.Pipeline, err)
_ = m.Nak()
return
}
}
switch {
case err != nil:
e.logf("%s is not taken: %v", m.Subject(), err)
case p.Run == "" && p.Group != "" && e.holdUntilRead(m):
return
case p.Run != "" || (p.Group != "" && !e.isRunner(p.Module)):
default:
if err := e.take(p, requiredPassed(p)); err != nil {
e.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
}
_ = m.Ack()
}
// hearGroup takes a group-ended: each member's end, passed only if the group passed. A run on request's (group `run-<id>`) delivers
// nothing: it drops the run's candidate assignment graph (A-235).
func (e *pipelineEnds) hearGroup(m jetstream.Msg) {
g, err := mprc.GroupEnded(m.Data())
if err != nil {
e.logf("%s is not taken: %v", m.Subject(), err)
_ = m.Ack()
return
}
if strings.HasPrefix(g.Group, runGroupPrefix) {
if e.runEnded != nil {
if err := e.runEnded(g.Group); err != nil {
e.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
}
_ = m.Ack()
return
}
for _, p := range g.Pipelines {
if err := e.take(p, g.Outcome == mpr.GroupEndedOutcomePassed && requiredPassed(p)); err != nil {
e.logf("%s: %v; it is heard again", m.Subject(), err)
_ = m.Nak()
return
}
}
_ = m.Ack()
}
// hearEnds registers the two events on the assigner's hub.
func hearEnds(hub *process.EventHub, e *pipelineEnds) error {
if err := hub.Handle(pipelineEndedSubject, e.hearPipeline); err != nil {
return fmt.Errorf("%s: %w", pipelineEndedSubject, err)
}
if err := hub.Handle(groupEndedSubject, e.hearGroup); err != nil {
return fmt.Errorf("%s: %w", groupEndedSubject, err)
}
return nil
}
// writtenTools is the tool assigner_written: every key of the state written, with its end.
func writtenTools(st store) []stdio.Tool {
return []stdio.Tool{{Name: writtenTool, Description: "the pipeline ends the assigner's wants follow: per module and watched branch, the source revision and end count of the newest end heard, whether it passed and whether the wants were written from it; with why, why each want is what it is (as assigner_why).",
return []stdio.Tool{{Name: writtenTool, Description: "the pipeline ends the assigner's wants follow: per module and watched branch, the newest version released whose pipeline passed, with its pipeline and rank; per pipeline whose wants are written tier by tier, its tier progress (tier, since, movers); with why, why each want is what it is (as assigner_why).",
Input: schema(map[string]string{"why": "true: why each want is what it is", "module": "with why: a module's name", "node": "with why: a node's name"}, nil, "why"),
Run: func(args map[string]any) (any, error) {
if args["why"] == true || args["why"] == "true" {
@@ -365,7 +307,7 @@ func writtenTools(st store) []stdio.Tool {
return nil, err
}
sort.Strings(ks)
out := map[string]End{}
out := map[string]any{}
for _, k := range ks {
if strings.HasPrefix(k, whyPrefix) {
continue // a want's why (why.go), read by assigner_why
@@ -374,6 +316,13 @@ func writtenTools(st store) []stdio.Tool {
if err != nil || !ok {
continue
}
if isTierKey(k) { // a pipeline's tier progress (tiers.go)
var t tierProgress
if json.Unmarshal(raw, &t) == nil {
out[k] = t
}
continue
}
var e End
if json.Unmarshal(raw, &e) == nil {
out[k] = e
@@ -383,56 +332,6 @@ func writtenTools(st store) []stdio.Tool {
}}}
}
// branchesOf is the watched branches the placements of module chose, each once; the default branch when none names one.
func (e *pipelineEnds) branchesOf(module string, placed map[string]map[string]string) []string {
if !e.following() {
return nil
}
seen := map[string]bool{}
var out []string
for _, b := range placed[module] {
b = e.branchOf(module, b)
if !seen[b] {
seen[b] = true
out = append(out, b)
}
}
if len(out) == 0 {
out = append(out, e.branchOf(module, ""))
}
sort.Strings(out)
return out
}
// mayWant says whether module's wants may name fp: a pipeline passed at fp on every branch, or the wants name fp already
// (a node placed later, a module taken away).
func (e *pipelineEnds) mayWant(module, fp string, branches []string, wanted map[string]mwc.Want) bool {
if !e.following() {
return true
}
for _, w := range wanted {
if w.Fp == fp {
return true
}
}
for _, b := range branches {
if !e.passedAt(module, b, fp) {
return false
}
}
return true
}
// wrote marks the end the wants of module were written from.
func (e *pipelineEnds) wrote(module, fp string, branches []string) {
if !e.following() {
return
}
for _, b := range branches {
e.markWritten(module, b, fp)
}
}
// following says whether the wants follow the pipeline ends yet; a nil follower never does.
func (e *pipelineEnds) following() bool { return e != nil && e.on.Load() }
@@ -454,7 +353,7 @@ func (e *pipelineEnds) registered(reg mpcat.Registration, gone bool) {
prefix := keys.EscapeName(reg.Module) + "."
for _, k := range kept {
rest, ok := strings.CutPrefix(k, prefix)
if !ok {
if !ok || isTierKey(k) || strings.HasPrefix(k, whyPrefix) {
continue
}
branch, err := keys.UnescapeName(rest)
@@ -476,7 +375,7 @@ func (e *pipelineEnds) registered(reg mpcat.Registration, gone bool) {
// followRegistrations follows the registrations through the seat mesh-catalog (design 47 G §353): a first view of its verb
// and each registration-changed on the hub. It returns when the hub's handler is registered; the first view is asked on its own
// goroutine, the wants keep the trunk-only form until a registration is heard.
// goroutine.
func followRegistrations(ctx context.Context, hub *process.EventHub, call mcc.Call, e *pipelineEnds) error {
regs := mcc.NewRegistrations(call)
regs.Follower.Logf = e.logf
@@ -4,35 +4,24 @@ import (
"context"
"encoding/json"
"fmt"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
plc "mesh-delivery-assigner/internal/assignment"
"slices"
"strings"
"testing"
"time"
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"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"
"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"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"mesh-delivery-assigner/internal/assigngraph"
plc "mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
mws "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
)
// memEnds is endStore over a map, with revisions.
@@ -72,250 +61,156 @@ func (m *heardMsg) Subject() string { return m.subject }
func (m *heardMsg) Ack() error { m.acked = true; return nil }
func (m *heardMsg) Nak() error { m.naked = true; return nil }
func pipe(module, branch string, source, count int64, fp, outcome string, steps ...mpr.StepResult) mpr.PipelineEnded {
return mpr.PipelineEnded{Module: module, Branch: branch, Source: source, EndCount: count, Fingerprint: fp, Outcome: outcome, Steps: steps,
Pipeline: branch + "." + module, Commit: "c"}
// mover is one mover at its pipeline's end, its required unit step ending outcome.
func mover(module, fp, version string, tier int64, outcome string) mpr.MoverEnded {
return mpr.MoverEnded{Module: module, Fingerprint: fp, Version: version, Tier: tier,
Steps: []mpr.StepResult{{Step: "unit", Status: mpr.StepResultStatusRequired, Outcome: outcome, Module: module}}}
}
func step(status, outcome string) mpr.StepResult {
return mpr.StepResult{Step: "unit", Status: status, Outcome: outcome}
// ended is the pipeline-ended of the take-in of source on branch, its movers given.
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,
Pipeline: fmt.Sprintf("%s.%d", branch, source)}
}
// Design 47 G §29, §35, §325, §352 (tests 66, 67, 89): a want follows a passed pipeline, by compare-and-set per module and branch.
func TestAWantFollowsAPassedPipeline(t *testing.T) {
const fp1, fp2 = "fp1", "fp2"
// A6/AC1 to AC3 (design 47 H §750, H-A-3): a passed pipeline keeps each mover's released version as the newest of its module on
// the branch, with the pipeline and the mover's tier; a failed pipeline, a mover whose required step failed, one that released
// no version, an older version, the same one again and a run on request keep nothing.
func TestThePassedVersionIsKept(t *testing.T) {
pass, fail := mpr.PipelineEndedOutcomePassed, mpr.PipelineEndedOutcomeFailed
req, opt := mpr.StepResultStatusRequired, mpr.StepResultStatusOptional
ok, failed, nothing := mpr.StepResultOutcomePassed, mpr.StepResultOutcomeFailed, mpr.StepResultOutcomeNothingToRun
for _, c := range []struct {
name string
ends []mpr.PipelineEnded
group *mpr.GroupEnded
module string
branch string
fp string
may bool
name string
ends []mpr.PipelineEnded
want *End // nil: none kept for web on main
}{
{"a failed required step writes no want", []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, fail, step(req, "failed"))}, nil, "web", "main", fp1, false},
{"a pipeline passed writes", []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, pass, step(req, "passed"))}, nil, "web", "main", fp1, true},
{"a failed optional step holds nothing", []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, pass, step(req, "passed"), step(opt, "failed"))}, nil, "web", "main", fp1, true},
{"a pipeline passed at another fingerprint", []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, pass)}, nil, "web", "main", fp2, false},
{"an older revision ending after a newer one writes nothing", []mpr.PipelineEnded{pipe("web", "main", 6, 1, fp2, fail), pipe("web", "main", 5, 1, fp1, pass)}, nil, "web", "main", fp1, false},
{"another branch writes its own", []mpr.PipelineEnded{pipe("web", "main", 6, 1, fp2, fail), pipe("web", "beta", 5, 1, fp1, pass)}, nil, "web", "beta", fp1, true},
{"a later end of the same revision writes", []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, fail, step(req, "failed")), pipe("web", "main", 5, 2, fp1, pass, step(req, "passed"))}, nil, "web", "main", fp1, true},
{"the same end again after a later one keeps the later", []mpr.PipelineEnded{pipe("web", "main", 5, 2, fp1, pass), pipe("web", "main", 5, 1, fp1, fail)}, nil, "web", "main", fp1, true},
{"a member's own end writes nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded { p := pipe("web", "main", 5, 1, fp1, pass); p.Group = "g"; return p }()}, nil, "web", "main", fp1, false},
{"a group ended passed writes its members", nil, &mpr.GroupEnded{Branch: "main", Group: "g", Outcome: mpr.GroupEndedOutcomePassed, Pipelines: []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, pass)}}, "web", "main", fp1, true},
{"a group ended failed writes none", nil, &mpr.GroupEnded{Branch: "main", Group: "g", Outcome: mpr.GroupEndedOutcomeFailed, Pipelines: []mpr.PipelineEnded{pipe("web", "main", 5, 1, fp1, pass)}}, "web", "main", fp1, false},
{"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}},
{"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}},
{"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},
{"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},
{"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}},
{"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}},
{"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.Run = "r1"
return p
}()}, nil},
} {
woken := 0
e := newPipelineEnds(newMemEnds(), func() { woken++ }, t.Logf)
e.on.Store(true)
e := newPipelineEnds(newMemEnds(), func() {}, t.Logf)
for _, p := range c.ends {
if p.Group != "" {
continue // heard and ignored, as hearPipeline does
}
if err := e.take(p, requiredPassed(p)); err != nil {
t.Fatal(err)
if _, err := e.take(p); err != nil {
t.Fatalf("%s: %v", c.name, err)
}
}
if g := c.group; g != nil {
for _, p := range g.Pipelines {
if err := e.take(p, g.Outcome == mpr.GroupEndedOutcomePassed && requiredPassed(p)); err != nil {
t.Fatal(err)
}
}
}
if got := e.mayWant(c.module, c.fp, []string{c.branch}, nil); got != c.may {
t.Errorf("%s: may want = %v, want %v", c.name, got, c.may)
got, kept := e.endOf("web", "main")
switch {
case c.want == nil && kept:
t.Errorf("%s: kept %+v", c.name, got)
case c.want != nil && (!kept || got != *c.want):
t.Errorf("%s: kept %+v (%v), want %+v", c.name, got, kept, *c.want)
}
}
// A run on request's group-ended (group run-<id>, A-235) writes no want and drops the run's candidate; a drop that fails is
// heard again.
{
e := newPipelineEnds(newMemEnds(), func() {}, t.Logf)
e.on.Store(true)
var dropped []string
fail := false
e.runEnded = func(group string) error {
dropped = append(dropped, group)
if fail {
return fmt.Errorf("the bucket is not open")
}
return nil
}
raw, _ := json.Marshal(mpr.GroupEnded{V: 1, Branch: "main", Group: "run-7", Outcome: mpr.GroupEndedOutcomePassed,
Pipelines: []mpr.PipelineEnded{func() mpr.PipelineEnded { p := pipe("web", "main", 5, 1, fp1, pass); p.Run = "7"; return p }()}})
m := &heardMsg{data: raw, subject: "mesh.seat.mesh-pipeline-runner.event.group-ended.x"}
e.hearGroup(m)
if e.mayWant("web", fp1, []string{"main"}, nil) || !slices.Equal(dropped, []string{"run-7"}) || !m.acked {
t.Errorf("a run's group-ended: may want %v, dropped %v, acked %v; want no want, run-7 dropped, acked",
e.mayWant("web", fp1, []string{"main"}, nil), dropped, m.acked)
}
fail = true
m = &heardMsg{data: raw, subject: m.subject}
e.hearGroup(m)
if !m.naked {
t.Error("a run's candidate not dropped is not heard again")
// The same end heard again changes nothing and wakes nothing; a run on request's end drops its candidate.
woken := 0
e := newPipelineEnds(newMemEnds(), func() { woken++ }, t.Logf)
var dropped []string
e.runEnded = func(group string) error { dropped = append(dropped, group); return nil }
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))
for range 2 {
raw, _ := json.Marshal(p)
m := &heardMsg{data: raw, subject: "mesh.seat.mesh-pipeline-runner.event.pipeline-ended.main.5"}
e.hearPipeline(m)
if !m.acked {
t.Error("the end was not acknowledged")
}
}
// A-334 (§29, §65, §268): in a group take-in that changes the runner, the runner's member (the holder of the seat
// mesh-pipeline-runner, read from the acting edges) is wanted on its own pipeline-ended once it passed, ahead of the group;
// the other members wait for group-ended.
{
e := newPipelineEnds(newMemEnds(), func() {}, t.Logf)
e.on.Store(true)
heard := func(p mpr.PipelineEnded) *heardMsg {
p.Group = "g"
raw, _ := json.Marshal(p)
m := &heardMsg{data: raw, subject: "mesh.seat.mesh-pipeline-runner.event.pipeline-ended.x"}
e.hearPipeline(m)
return m
}
hear := func(p mpr.PipelineEnded) {
if m := heard(p); !m.acked {
t.Errorf("the pipeline-ended of %s is not acknowledged", p.Module)
}
}
// The runner's end heard before a pass read the graph is held, unacknowledged, and taken once the runner is read.
early := heard(pipe("runner", "main", 5, 1, "fp-runner", pass, step(req, "passed")))
if early.acked || early.naked || e.mayWant("runner", "fp-runner", []string{"main"}, nil) {
t.Fatalf("the runner's end before the graph is read: acked %v, naked %v, wanted %v; want it held", early.acked, early.naked,
e.mayWant("runner", "fp-runner", []string{"main"}, nil))
}
e.setRunner(assigngraph.Runner([]mws.AssignmentEntry{{Node: "ace", Module: "web", Edges: []mws.Edge{
{Kind: assigngraph.EdgeActing, Node: "ace", Module: "runner", Seat: mpr.Seat, Step: "pipeline"}}}}))
if !early.acked {
t.Error("the runner's end held until the graph was read is not taken once it is")
}
hear(pipe("web", "main", 5, 1, fp1, pass, step(req, "passed")))
if !e.mayWant("runner", "fp-runner", []string{"main"}, nil) || e.mayWant("web", fp1, []string{"main"}, nil) {
t.Errorf("a group changing the runner: may want the runner %v, web %v; want the runner ahead of the group and web not yet",
e.mayWant("runner", "fp-runner", []string{"main"}, nil), e.mayWant("web", fp1, []string{"main"}, nil))
}
hear(pipe("runner", "main", 6, 1, "fp-runner-2", fail, step(req, "failed")))
if e.mayWant("runner", "fp-runner-2", []string{"main"}, nil) {
t.Error("the runner's member that failed is wanted")
}
}
// Design 47 G A-428: the runner's first start skips the gate while no module claiming the seat runs; another module never
// does, and a runner running anywhere (stopped ones aside) closes it; with no running heard the gate stands.
manifests := map[string]catalogue.Manifest{"runner": {Claims: []catalogue.Claim{{Name: mpr.Seat}}}, "web": {}}
none := map[string]map[string]nodeengine.Running{"ace": {"web": {Fingerprint: fp1}}}
if !runnerFirstStart("runner", manifests, none) || runnerFirstStart("web", manifests, none) || runnerFirstStart("runner", manifests, nil) {
t.Error("the runner's first start: the runner skips the gate, another module or an unknown world does not")
}
if runnerFirstStart("runner", manifests, map[string]map[string]nodeengine.Running{"novox": {"runner": {Fingerprint: "fp-runner"}}}) ||
!runnerFirstStart("runner", manifests, map[string]map[string]nodeengine.Running{"novox": {"runner": {Stopped: true}}}) {
t.Error("a runner running closes the gate's opening; one stopped does not")
}
// A want that names the fingerprint already is not held by a later failure (a node placed afterwards gets it).
e := newPipelineEnds(newMemEnds(), func() {}, t.Logf)
e.on.Store(true)
if !e.mayWant("web", fp1, []string{"main"}, map[string]mwc.Want{"g14": {Fp: fp1}}) {
t.Error("a want naming the fingerprint was held")
}
// markWritten keeps the end and says it was written from; a newer end replaces it unwritten.
st := newMemEnds()
e = newPipelineEnds(st, func() {}, t.Logf)
e.on.Store(true)
_ = e.take(pipe("web", "main", 5, 1, fp1, pass), true)
e.wrote("web", fp1, []string{"main"})
var end End
_ = json.Unmarshal(st.vals[endKey("web", "main")], &end)
if !end.Written || end.Source != 5 {
t.Errorf("end = %+v, want written at source 5", end)
}
_ = e.take(pipe("web", "main", 6, 1, fp2, pass), true)
end = End{}
_ = json.Unmarshal(st.vals[endKey("web", "main")], &end)
if end.Written || end.Source != 6 {
t.Errorf("a newer end = %+v, want unwritten at source 6", end)
run := p
run.Run = "r1"
raw, _ := json.Marshal(run)
e.hearPipeline(&heardMsg{data: raw, subject: "mesh.seat.mesh-pipeline-runner.event.pipeline-ended.main.5"})
if woken != 1 || !slices.Equal(dropped, []string{runGroupPrefix + "r1"}) {
t.Errorf("woken %d (want 1), dropped %v (want the run's candidate)", woken, dropped)
}
}
// Design 47 G §29: the wants of a pass follow a pipeline: with the follower on, a module whose fingerprint no pipeline passed at
// gets no want and one a pipeline passed at gets it; with it off (nil, the trunk-only want) the pass is as before.
func TestAPassWritesNoWantWithoutAPassedPipeline(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
// 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.
func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) {
fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64)
for _, c := range []struct {
name string
follow bool
passed bool
want bool
}{{"the trunk-only want", false, false, true}, {"no pipeline passed", true, false, false}, {"a pipeline passed", true, true, true}} {
for _, passed := range []bool{false, true} {
wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
p.say = func(oc.Condition) error { return nil }
mdigest := strings.Repeat("e", 64)
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp, Manifest: mdigest, Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, trunkBranch, "web", mod)
p.w.manifests[mdigest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web"}}
endDone(t, p.w, "web", fp, mdigest)
gkey, _ := grantsstate.PartGrantKey("web", fp)
grant, _ := grantsstate.EncodeGrant(grantsstate.Grant{})
p.w.put(buckets.Grants, gkey, grant)
digest := "sha256:" + strings.Repeat("c", 64)
have, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: digest, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
p.w.put(buckets.Have, "g14.web", have)
composes(t, p.w, "g14", digest)
p.w.manifests[mdigest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web", Requires: []string{"database"}}}
placeOn(t, p.w, "g14", "web")
on := true
p.w.heardPresence("g14", !on, time.Now())
if c.follow {
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk = p.w.trunkName
p.ends.on.Store(true)
if c.passed {
_ = p.ends.take(pipe("web", trunkBranch, 5, 1, fp, mpr.PipelineEndedOutcomePassed), true)
}
placeOn(t, p.w, "ace", "web")
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk = p.w.trunkName
if passed {
_, _ = p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("web", fp, "0.1.2", 2, mpr.StepResultOutcomePassed)))
}
p.wants(context.Background())
key, _ := mwc.WantKey("g14", "web")
if _, got := wantsKV.values[key]; got != c.want {
t.Errorf("%s: a want written = %v, want %v", c.name, got, c.want)
}
if c.follow && c.passed {
raw, _, _ := p.ends.st.get(endKey("web", trunkBranch))
var end End
_ = json.Unmarshal(raw, &end)
if !end.Written {
t.Errorf("%s: the end was not marked written", c.name)
for _, node := range []string{"g14", "ace"} {
key, _ := mwc.WantKey(node, "web")
raw, got := wantsKV.values[key]
if got != passed {
t.Errorf("passed %v: a want on %s written = %v", passed, node, got)
continue
}
if !passed {
continue
}
if w, err := mwc.DecodeWant(raw); err != nil || w.Fp != fp || w.Version != "0.1.2" || w.Pipeline != trunkBranch+".5" || w.Rank != 2 {
t.Errorf("the want on %s = %+v (%v)", node, w, err)
}
}
}
}
// Design 47 G §95, §130, §353, §352 (test 100): the wants keep the trunk-only form until the first registration is heard and
// switch on it; a branch a registration no longer watches loses its end, and its first branch is a placement's default.
func TestTheWantsSwitchOnTheFirstRegistration(t *testing.T) {
// Design 47 G §353, §352: a registration's first branch is a placement's default, and a branch it no longer watches loses its
// end; a registration gone loses them all.
func TestARegistrationNamesTheDefaultBranch(t *testing.T) {
st := newMemEnds()
woken := 0
e := newPipelineEnds(st, func() { woken++ }, t.Logf)
e.trunk = func() string { return trunkBranch }
_ = e.take(pipe("web", "main", 5, 1, "fp1", mpr.PipelineEndedOutcomeFailed), false)
_ = e.take(pipe("web", "beta", 5, 1, "fp1", mpr.PipelineEndedOutcomePassed), true)
if e.following() || !e.mayWant("web", "fp1", []string{"main"}, nil) {
t.Fatal("the follower held a want before any registration")
}
pass := mpr.PipelineEndedOutcomePassed
_, _ = e.take(ended("main", 5, pass, mover("web", "fp1", "0.1.1", 1, mpr.StepResultOutcomePassed)))
_, _ = e.take(ended("beta", 5, pass, mover("web", "fp2", "0.1.2", 1, mpr.StepResultOutcomePassed)))
e.registered(mpcat.Registration{Module: "web", Branches: []string{"beta"}}, false)
if !e.following() || woken == 0 {
t.Error("the first registration did not switch the wants on")
endsKept := func() (n int) { // a pipeline's tier progress is not a module's end
for k := range st.vals {
if !isTierKey(k) {
n++
}
}
return n
}
if e.mayWant("web", "fp1", []string{"main"}, nil) || !e.mayWant("web", "fp1", []string{"beta"}, nil) {
t.Error("after the switch the wants did not follow the ends")
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", ""))
}
if len(st.vals) != 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", len(st.vals), e.branchOf("web", ""))
if tg, ok := e.target("web", ""); !ok || tg.Fp != "fp2" {
t.Errorf("the default branch's target = %+v %v", tg, ok)
}
e.registered(mpcat.Registration{Module: "web"}, true)
if len(st.vals) != 0 {
t.Errorf("a registration gone left %d ends", len(st.vals))
if endsKept() != 0 {
t.Errorf("a registration gone left %d ends", endsKept())
}
}
// Design 47 G §14, §184 (test 68): a node's entry is computed from the catalog half of the branch its placement names, so a
// change on `beta` moves only the want of the node whose placement chose `beta`.
func TestACommitOnBetaMovesOnlyTheNodeThatChoseBeta(t *testing.T) {
// Design 47 G §14, §184 (test 68): a node's want follows the branch its placement names, so a version passed on `beta` moves only
// the want of the node whose placement chose `beta`.
func TestAVersionOnBetaMovesOnlyTheNodeThatChoseBeta(t *testing.T) {
fp := func(c string) string { return meshcatalogclient.SourcePrefix2 + strings.Repeat(c, 64) }
wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
@@ -323,15 +218,8 @@ func TestACommitOnBetaMovesOnlyTheNodeThatChoseBeta(t *testing.T) {
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk = p.w.trunkName
p.ends.registered(mpcat.Registration{Module: "web", Branches: []string{"main", "beta"}}, false)
digest := "sha256:" + strings.Repeat("c", 64)
on := true
for _, node := range []string{"g14", "ace"} {
composes(t, p.w, node, digest)
p.w.heardPresence(node, !on, time.Now())
}
for node, branch := range map[string]string{"g14": "", "ace": "beta"} {
pl := mma.Assignments{Node: node, Modules: []mma.PlacedModule{{Module: "web", Branch: branch}}}
values, err := mmac.AssignmentsValues(pl)
values, err := mmac.AssignmentsValues(mma.Assignments{Node: node, Modules: []mma.PlacedModule{{Module: "web", Branch: branch}}})
if err != nil {
t.Fatal(err)
}
@@ -339,24 +227,10 @@ func TestACommitOnBetaMovesOnlyTheNodeThatChoseBeta(t *testing.T) {
p.w.put(plc.AssignmentsBucket(), key, raw)
}
}
// publish makes the half of branch name web at fingerprint f: built, granted and passed by its pipeline.
publish := func(branch, f string, source int64) {
mdigest := strings.Repeat("e", 62) + fmt.Sprintf("%02d", source)
if branch == "beta" {
mdigest = strings.Repeat("f", 62) + fmt.Sprintf("%02d", source)
}
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: f, Manifest: mdigest, Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, branch, "web", mod)
p.w.manifests[mdigest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web"}}
endDone(t, p.w, "web", f, mdigest)
gkey, _ := grantsstate.PartGrantKey("web", f)
grant, _ := grantsstate.EncodeGrant(grantsstate.Grant{})
p.w.put(buckets.Grants, gkey, grant)
_ = p.ends.take(pipe("web", branch, source, 1, f, mpr.PipelineEndedOutcomePassed), true)
}
run := func(node, f string) {
have, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: f, Composed: digest, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
p.w.put(buckets.Have, node+".web", have)
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp("a"), Manifest: strings.Repeat("e", 64), Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, "main", "web", mod)
passed := func(branch, f, version string, source int64) {
_, _ = p.ends.take(ended(branch, source, mpr.PipelineEndedOutcomePassed, mover("web", f, version, 1, mpr.StepResultOutcomePassed)))
}
fpWant := func(node string) string {
key, _ := mwc.WantKey(node, "web")
@@ -366,18 +240,16 @@ func TestACommitOnBetaMovesOnlyTheNodeThatChoseBeta(t *testing.T) {
}
return w.Fp
}
publish("main", fp("a"), 5)
publish("beta", fp("b"), 5)
run("g14", fp("a"))
run("ace", fp("b"))
passed("main", fp("a"), "0.1.1", 5)
passed("beta", fp("b"), "0.2.1", 5)
p.wants(context.Background())
if fpWant("g14") != fp("a") || fpWant("ace") != fp("b") {
t.Fatalf("each node is wanted at its branch's build: g14 %s, ace %s", fpWant("g14"), fpWant("ace"))
}
publish("beta", fp("d"), 6)
passed("beta", fp("d"), "0.2.2", 6)
p.wants(context.Background())
if fpWant("g14") != fp("a") || fpWant("ace") != fp("d") {
t.Errorf("a commit on beta moves only ace: g14 %s (want main's), ace %s (want beta's new)", fpWant("g14"), fpWant("ace"))
t.Errorf("a version on beta moves only ace: g14 %s (want main's), ace %s (want beta's new)", fpWant("g14"), fpWant("ace"))
}
}
@@ -411,40 +283,3 @@ func TestTheCatalogHalfIsTakenInPerBranch(t *testing.T) {
t.Error("a module taken out of beta's half leaves main's")
}
}
// Design 47 G §379, §526: a want held at an older build, the trunk's newer fingerprint having passed no pipeline, is rewritten
// with that build's released version (and parts for an engine that reads them), the rest of the want kept; no want names the
// unpassed fingerprint (novox 2026-11-16, mesh-hand-acts 0.1.13 at 4eb3cf48).
func TestAWantHeldAtAnOlderBuildNamesItsReleaseWithoutAPassedPipeline(t *testing.T) {
old := meshcatalogclient.SourcePrefix2 + strings.Repeat("4", 64)
fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("9", 64)
wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
p.say = func(oc.Condition) error { return nil }
mdigest := strings.Repeat("e", 64)
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp, Manifest: mdigest, Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, trunkBranch, "web", mod)
p.w.manifests[mdigest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web"}}
endRaw, _ := json.Marshal(builds.BuildEnded{Module: "web", Fingerprint: old, Outcome: builds.BuildDone, Manifest: mdigest, Made: map[string]string{"tools": "sha256:1c"}})
if err := p.w.ends.put(endRaw); err != nil {
t.Fatal(err)
}
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "web", Source: 962, Version: "0.1.13", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "tools", Digest: "sha256:1c"}}})
if err := p.w.released.put(rel); err != nil {
t.Fatal(err)
}
placeOn(t, p.w, "g14", "web")
key, _ := mwc.WantKey("g14", "web")
held, _ := mwc.EncodeWant(mwc.Want{Fp: old, Self: true})
wantsKV.values[key] = held
p.w.put(buckets.Wants(), key, held)
p.w.heardPresence("g14", false, time.Now())
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk = p.w.trunkName
p.ends.on.Store(true)
p.wants(context.Background())
got, err := mwc.DecodeWant(wantsKV.values[key])
if err != nil || got.Fp != old || got.Version != "0.1.13" || !got.Self {
t.Errorf("the held want = %+v, %v; want %s at 0.1.13, self kept", got, err, old)
}
}
@@ -1,95 +0,0 @@
package main
import (
"context"
"fmt"
"sort"
"mesh-delivery-assigner/internal/buckets"
"mesh-delivery-assigner/internal/puts"
)
// placementBy is who a put the placement's build makes names as its asker: the placement, whose proposal the operator
// approved, is the warrant (design 47 *Going back is one act*; ADR 0666 §24).
const placementBy = "the placement"
// placementPuts makes each placed module's `build` a held put of that build, and releases a put the placement made once its
// placement names that build no more (design 47 line 912: "a return to an earlier build is one value in the placement, the
// module's `build` in its placement key, set by a placement proposal"; ADR 0666 §24; B-K1). The put then goes its own steps
// (the builder's build, the composition, an ask where the module's policy needs one, the want, holding) and is read with
// `assigner_puts` and released with `assigner_release` like any other; a placement's build the builder never built is refused
// by its build step, said in the put's words. A put asked by a person stands until the placement names another build.
func (p *passer) placementPuts(ctx context.Context) {
kv := p.kvs[buckets.Puts()]
if kv == nil {
return
}
now := p.clock().UTC()
named := map[string]string{} // put key -> the build its placement names
for node, a := range p.w.assignments() {
for _, m := range a.Modules {
if m.Build == "" {
continue
}
if key, err := puts.Key(node, m.Module); err == nil {
named[key] = m.Build
}
}
}
held := p.w.read(buckets.Puts())
keys := make([]string, 0, len(named)+len(held))
for k := range named {
keys = append(keys, k)
}
for k := range held {
if _, there := named[k]; !there {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, key := range keys {
build, names := named[key]
var before *puts.Put
if raw, ok := held[key]; ok {
if got, err := puts.Decode(raw); err == nil {
before = &got
}
}
var next puts.Put
switch {
case names && before != nil && before.FP == build:
continue // made already, or a person's put of the same build: it goes its own steps, ended or not
case names:
words := fmt.Sprintf("asked by %s: it names build %s of %s", placementBy, shortFP(build), key)
if before != nil && !puts.Ended(before.Step) {
words += fmt.Sprintf("; it replaces the put of %s, which stood at %s", shortFP(before.FP), before.Step)
}
next = puts.Put{FP: build, Hold: true, Why: "the placement names this build (ADR 0666 §24)", By: placementBy, At: now}.Said(now, puts.Asked, words)
case before != nil && before.By == placementBy && !puts.Ended(before.Step):
next = before.Said(now, puts.Released, fmt.Sprintf("released by %s: it names no build of its own any more; the assigner's rules write the want again", placementBy))
default:
continue
}
data, err := puts.Encode(next)
if err != nil {
p.logf("the placement's put %s is not written: %v", key, err)
continue
}
if before == nil {
_, err = kv.Create(ctx, key, data)
} else if e, gerr := kv.Get(ctx, key); gerr != nil {
err = gerr
} else {
_, err = kv.Update(ctx, key, data, e.Revision())
}
if err != nil {
p.logf("the placement's put %s could not be written, and is written at the next pass: %v", key, err)
continue
}
p.w.put(buckets.Puts(), key, data)
p.logf("put %s: %s: %s", key, next.Step, next.Words)
if p.acts != nil {
p.acts.say(key, next)
}
}
}
@@ -0,0 +1,204 @@
package main
import (
"context"
"encoding/json"
"fmt"
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
"strings"
"testing"
"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/seats/meshbroker"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"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"
"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"
"git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"mesh-delivery-assigner/internal/assigngraph"
plc "mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
)
// orderFP is a fingerprint of the form the trunk keeps, made of one letter.
func orderFP(c string) string {
return meshcatalogclient.SourcePrefix2 + strings.Repeat(fmt.Sprintf("%x", c[0]&15), 64)
}
// orderMod is one module of an order test: the fingerprint it runs on ace and the one the trunk holds, the form of its kept data at each
// fingerprint (0: it keeps none), the seats it holds and the source revision of its trunk value.
type orderMod struct {
name string
run, trunk string
forms map[string]int
holds []string
}
type orderFixture struct {
t *testing.T
p *passer
wants *memKV
events []string
bodies []meshwants.Wait
answers chan struct{}
}
// newOrderFixture is a pass on node ace, which composes its own modules, with each module running its fingerprint healthy, built and
// granted at the trunk's, an older want, the catalog's entries answered and each held seat as the assignments say it. history lists the
// fingerprints of each module by assignment graph revision, oldest first (the objects Reverted reads).
func newOrderFixture(t *testing.T, mods []orderMod, history ...map[string]string) *orderFixture {
t.Helper()
ctx := context.Background()
f := &orderFixture{t: t, wants: &memKV{values: map[string][]byte{}}, answers: make(chan struct{}, 64)}
f.p = newPasser(kvSet{buckets.Wants(): f.wants, buckets.Asks(): &memKV{values: map[string][]byte{}}, buckets.Waits(): &memKV{values: map[string][]byte{}}}, time.Now())
p := f.p
p.logf = t.Logf
p.say = func(oc.Condition) error { return nil }
p.publishWants = func(event string, body any, id string) error {
f.events = append(f.events, event)
f.bodies = append(f.bodies, body.(meshwants.Wait))
return nil
}
digest := "sha256:" + strings.Repeat("c", 64)
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk = p.w.trunkName
pl := mma.Assignments{Node: "ace"}
forms := map[string]int{} // by fingerprint: each module's own
modules := []string{}
for _, m := range mods {
modules = append(modules, m.name)
pl.Modules = append(pl.Modules, mma.PlacedModule{Module: m.name})
for _, seat := range m.holds {
scope := "node"
if seat != catalogue.BackupSeat && seat != nodeengine.Seat {
scope = "mesh"
}
pl.Holds = append(pl.Holds, mma.Holding{Claim: seat, Module: m.name, Scope: scope})
}
for fp, form := range m.forms {
forms[fp] = form
}
mdigest := fmt.Sprintf("%064x", len(modules))
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: m.trunk, Manifest: mdigest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, trunkBranch, m.name, mod)
p.w.manifests[mdigest] = parsed{module: m.name, manifest: catalogue.Manifest{Module: m.name}}
endDone(t, p.w, m.name, m.trunk, mdigest)
gkey, _ := grantsstate.PartGrantKey(m.name, m.trunk)
grant, _ := grantsstate.EncodeGrant(grantsstate.Grant{})
p.w.put(buckets.Grants, gkey, grant)
f.runs(m.name, m.run)
// The trunk's build is released with a passed pipeline (design 47 H §750).
_, _ = 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)
old, _ := mwc.EncodeWant(mwc.Want{Fp: m.run, Self: true})
p.w.put(buckets.Wants(), wkey, old)
f.wants.values[wkey] = old
}
composes(t, p.w, "ace", digest)
values, err := mmac.AssignmentsValues(pl)
if err != nil {
t.Fatal(err)
}
for key, raw := range values {
p.w.put(plc.AssignmentsBucket(), key, raw)
}
p.w.heardPresence("ace", false, time.Now()) // ace is online: its last presence event heard is machine-back
objects := memObjects{}
for i, at := range history {
half := meshcatalogclient.Half{Revision: meshcatalog.CatalogRevision{Branch: trunkBranch, Kind: "trunk", Revision: int64(i + 1), Source: int64(i + 1)},
Entries: map[string]meshcatalog.CatalogEntry{}}
for _, module := range modules {
digest := fmt.Sprintf("sha256:%064x", (i+1)*1000+len(half.Entries))
half.Revision.Entries = append(half.Revision.Entries, meshcatalog.EntryRef{Module: module, Digest: digest})
half.Entries[module] = meshcatalog.CatalogEntry{Module: module, Fp: at[module]}
}
placed := mma.Assignments{Node: "ace"}
for _, module := range modules {
placed.Modules = append(placed.Modules, mma.PlacedModule{Module: module})
}
in := assigngraph.Inputs{Halves: map[string]meshcatalogclient.Half{trunkBranch: half}, FirstBranch: func(string) string { return trunkBranch },
Placements: map[string]mma.Assignments{"ace": placed}}
if _, _, err := assigngraph.Keep(ctx, objects, assigngraph.Compute(in), "test", time.Now()); err != nil {
t.Fatal(err)
}
}
p.graph = &graphKeeper{objects: objects}
p.entries = meshcatalogclient.NewEntries(func(_ string, body any) (json.RawMessage, error) {
in := body.(meshcatalog.EntryInput)
entry := meshcatalog.CatalogEntry{Module: "m", Fp: in.Fingerprint, Manifest: map[string]any{"module": "m"}}
if form := forms[in.Fingerprint]; form > 0 {
entry.Manifest = map[string]any{"module": "m", "state": []any{map[string]any{"name": "sessions", "form": form}}}
}
return json.Marshal(meshcatalog.EntryAnswer{Entry: entry})
})
p.entries.Changed = func(meshcatalogclient.EntryRow) { f.answers <- struct{}{} }
return f
}
// runs says module runs fp healthy on ace, heard as the node-engine seat's running and in the have.
func (f *orderFixture) runs(module, fp string) {
have, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: "sha256:" + strings.Repeat("c", 64), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
f.p.w.put(buckets.Have, "ace."+module, have)
f.p.w.running["ace."+module] = nodeengine.Running{Node: "ace", Module: module, Fingerprint: fp}
}
// pass makes a pass, and after it every catalog entry it asked is answered.
func (f *orderFixture) pass() {
f.t.Helper()
f.p.wants(context.Background())
asked := 0
for _, row := range f.p.entries.Rows() {
if row.State == meshcatalogclient.EntryAsked {
asked++
}
}
for range asked {
select {
case <-f.answers:
case <-time.After(10 * time.Second): // a bound on a failure only: the answers come at once
f.t.Fatal("an entry asked was not answered")
}
}
}
// wantAt is the fingerprint module is wanted at on ace.
func (f *orderFixture) wantAt(module string) string {
f.t.Helper()
key, _ := mwc.WantKey("ace", module)
w, err := mwc.DecodeWant(f.wants.values[key])
if err != nil {
f.t.Fatal(err)
}
return w.Fp
}
func (f *orderFixture) waits() []string {
var out []string
for key := range f.p.w.read(buckets.Waits()) {
out = append(out, key)
}
return out
}
// A3/AC1 (design 47 H §771, §764): given a module whose kept data's form changes while the new versions of the node-backup holder and
// of the bus module do not run, when the assigner passes, then the module is wanted at its new version, no `order.` key is kept and no
// wait is said: the order on a machine is its node-engine's apply order, by rank.
func TestNoWantWaitsForTheOrderOfADelivery(t *testing.T) {
f := newOrderFixture(t, []orderMod{
{name: "web", run: orderFP("a"), trunk: orderFP("b"), forms: map[string]int{orderFP("a"): 1, orderFP("b"): 2}},
{name: "backup", run: orderFP("e"), trunk: orderFP("f"), holds: []string{catalogue.BackupSeat}},
{name: "bus", run: orderFP("g"), trunk: orderFP("h"), holds: []string{meshbroker.Seat}},
})
f.pass()
f.pass()
if got := f.wantAt("web"); got != orderFP("b") || len(f.waits()) != 0 || len(f.events) != 0 {
t.Fatalf("web at %s, waits %v, events %v: want web at its new version, no wait kept or said", got, f.waits(), f.events)
}
}
@@ -42,8 +42,6 @@ type caller interface {
CallOn(node, key string, body any) (json.RawMessage, error)
// CallKept is Call for a kept call, safe to call again (process.Conn.CallKept; ADR 0668).
CallKept(key string, body any) (json.RawMessage, error)
// CallKeptOn is CallOn for a kept call, safe to call again (process.Conn.CallKeptOn; ADR 0668).
CallKeptOn(node, key string, body any) (json.RawMessage, error)
// CallFile is Call of a verb marked chunks, its answer read whole (process.Conn.CallFile; design 47 G A-291).
CallFile(key string, body any) (json.RawMessage, error)
Emit(eventType string, body any) error
@@ -106,7 +104,6 @@ func (p *passer) puts(ctx context.Context) {
if p.acts == nil {
return
}
p.placementPuts(ctx)
all := p.putsByModule()
defer func() { p.putWaits(ctx, p.putsByModule()) }()
if len(all) == 0 {
@@ -136,14 +133,6 @@ func (p *passer) puts(ctx context.Context) {
world := p.putWorld(node, module, put, manifest, assigned[node])
world.Snapshot, world.Snapshotting, world.SnapshotFailed = p.acts.state(id)
next := assign.StepPut(world)
// A held bus whose user list the rules moved on (ADR 0539 §7): the put follows the composition its want names.
if w, ok := wanted[module][node]; ok && w.Put && w.Fp == next.Put.FP && w.Composed != "" && w.Composed != next.Put.Composed &&
(next.Put.Step == puts.Wanted || next.Put.Step == puts.Holding) {
if d, _ := p.composedFor(node, module, w.Fp); d != nil && d.UserListOnly && d.Digest == w.Composed {
next.Put = next.Put.Said(world.Now, next.Put.Step, fmt.Sprintf("the bus's user list changed: the want names composition %s", shortHex(w.Composed)))
next.Put.Composed = w.Composed
}
}
// The bus's want is written only for the act the operator's yes bound (ADR 0546 clause 8).
if next.Put.Step == puts.Wanted && put.Step != puts.Wanted && world.Bus && next.Put.Ask != "" {
if err := p.performs(next.Put.Ask, assign.PutAct(node, module, next.Put.FP, next.Put.Composed)); err != nil {
@@ -0,0 +1,87 @@
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/nats-io/nats.go/jetstream"
wd "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/assignment"
)
// releaseHeard is one version-released heard: the version, each part's digest, the source revision and when it was said.
type releaseHeard struct {
Version string
Parts map[string]string
Source int64
At time.Time
}
// presenceOf reads one machine-away or machine-back: the machine and when it was said.
func presenceOf(data []byte) (string, time.Time, error) {
var e wd.MachineAwayEvent // machine-back has the same fields
if err := json.Unmarshal(data, &e); err != nil {
return "", time.Time{}, err
}
if e.Machine == "" {
return "", time.Time{}, fmt.Errorf("it names no machine: %s", data)
}
return e.Machine, e.At, nil
}
// hearReleases reads whole, from their first message, then follows, the catalog seat's version-released and the watchman's
// machine-away and machine-back (mesh-sdk process.FromFirst, A-233), never their state. A stream not heard is said as the assigner's finding, and what it carries is not known until
// the assigner starts again.
func hearReleases(ctx context.Context, js jetstream.JetStream, w *world, wake func(), findings assign.Findings, logf func(string, ...any)) {
acct := process.Account{Node: thisNode, Module: assignment.Module()}
nh := notHeardWriter(findings, logf)
for _, s := range []struct {
stream, words string
take func([]byte) error
}{
{meshcatalog.StreamVersionReleased, "no want names a released version", w.released.put},
{wd.StreamMachineAway, "no machine is known away, so a delivery waits for a machine that is away", func(data []byte) error {
m, at, err := presenceOf(data)
if err == nil {
w.heardPresence(m, true, at)
logf("%s is away (machine-away): a composition step does not compose it until its machine-back", m)
}
return err
}},
{wd.StreamMachineBack, "a machine once away is not known back", func(data []byte) error {
m, at, err := presenceOf(data)
if err == nil {
w.heardPresence(m, false, at)
logf("%s is back (machine-back): a composition step composes it again", m)
}
return err
}},
} {
take := s.take
cc, err := acct.HearSeatEvents(ctx, js, s.stream, func(m jetstream.Msg) {
if err := take(m.Data()); err != nil {
logf("%s is not kept: %v", m.Subject(), err)
}
if err := m.Ack(); err != nil {
logf("acknowledging %s: %v", m.Subject(), err)
}
wake()
}, logf, process.FromFirst())
if err != nil {
nh.NotHeard(s.stream, s.words+" until the assigner starts again", err)
continue
}
nh.Heard(s.stream)
go func() {
<-ctx.Done()
cc.Stop()
}()
}
}
@@ -0,0 +1,140 @@
package main
import (
"context"
"fmt"
"slices"
"strconv"
"strings"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"mesh-delivery-assigner/internal/assigngraph"
)
// The assignment graph revisions are removed when they are no longer current (design 47 H §764, H-A-86): the gate's pins of
// them went with its pinned, freed, heads-replaced and pins-stated (H-A-48), and with them the assigner's state pins and its
// tools assigner_pins and assigner_unpin. A revision that is not current (the newest the assigner wrote) is removed, its object
// and the entry objects no kept revision or candidate lists and no want or running build names (G §179), when a revision ceases
// to be current and once at the start. Never on a timer.
// revisionObjects is the object bucket of the revisions as the remover removes from it.
type revisionObjects interface {
assigngraph.Objects
Delete(ctx context.Context, name string) error
}
// revisionRemover removes the revisions that are not current.
type revisionRemover struct {
ctx context.Context
objects revisionObjects
// inUse says a want or a running build names the module's fingerprint (§179).
inUse func(module, fp string) bool
logf func(string, ...any)
}
// judge removes every revision that is not current; a removal that fails is said and made at the next judging.
func (k *revisionRemover) judge() {
if err := k.remove(); err != nil {
k.logf("the revisions that are not current are not removed: %v", err)
}
}
// trunkRevision is the revision an object of a trunk revision names, and whether it names one.
func trunkRevision(name string) (int64, bool) {
n, ok := strings.CutPrefix(name, "trunk.")
if !ok {
return 0, false
}
r, err := strconv.ParseInt(n, 10, 64)
return r, err == nil && r > 0
}
// remove removes each kept revision that is not current, and then the entries no kept revision or candidate lists and no want or
// running build names (design 47 G §179).
func (k *revisionRemover) remove() error {
names, err := k.objects.Names(k.ctx)
if err != nil {
return err
}
var kept []int64
for _, n := range names {
if r, ok := trunkRevision(n); ok {
kept = append(kept, r)
}
}
if len(kept) == 0 {
return nil
}
current := slices.Max(kept)
listed := map[string]bool{}
removed := 0
for _, r := range kept {
if r == current {
rev, err := assigngraph.ReadRevision(k.ctx, k.objects, r)
if err != nil {
return err
}
for _, e := range rev.Entries {
listed[e.Digest] = true
}
continue
}
if err := k.objects.Delete(k.ctx, assigngraph.TrunkObject(r)); err != nil {
return fmt.Errorf("revision %d: %w", r, err)
}
removed++
}
if removed == 0 {
return nil
}
// A run's candidate kept now lists its entries too, until its run's pipeline-ended drops it (A-201, A-235).
for _, n := range names {
group, heads, ok := meshwants.ParseAssignmentRevisionsByCandidateGroupHeadsKey(n)
if !ok {
continue
}
rev, err := assigngraph.ReadCandidate(k.ctx, k.objects, group, heads)
if err != nil {
return err
}
for _, e := range rev.Entries {
listed[e.Digest] = true
}
}
for _, n := range names {
digest, ok := strings.CutPrefix(n, "entry.")
if !ok || listed[digest] {
continue
}
e, err := assigngraph.ReadEntry(k.ctx, k.objects, digest)
if err != nil {
return err
}
if k.inUse != nil && k.inUse(e.Module, e.Fp) {
continue
}
if err := k.objects.Delete(k.ctx, n); err != nil {
return fmt.Errorf("the entry %s: %w", digest, err)
}
}
k.logf("%d assignment graph revisions not current are removed", removed)
return nil
}
// inUseOf says a want or a running build names the module's fingerprint, as the world holds them now.
func inUseOf(w *world) func(module, fp string) bool {
return func(module, fp string) bool {
for _, want := range w.wantsOf()[module] {
if want.Fp == fp {
return true
}
}
for _, mods := range w.runningNow() {
if r, ok := mods[module]; ok && r.Fingerprint == fp {
return true
}
}
return false
}
}
@@ -0,0 +1,53 @@
package main
import (
"context"
"encoding/json"
"testing"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"mesh-delivery-assigner/internal/assigngraph"
)
func (m memObjects) Delete(_ context.Context, name string) error { delete(m, name); return nil }
// Design 47 H §764, H-A-86: with the gate's pins gone, an assignment graph revision that is not current is removed, with the
// entries no kept revision or candidate lists and no want or running build names; the current revision, the entries it lists,
// a running build's entry and a run's kept candidate with its entries stay.
func TestARevisionNotCurrentIsRemoved(t *testing.T) {
objects := memObjects{}
entry := func(module, fp string) string {
e := meshwants.AssignmentEntry{Node: "n1", Module: module, Fp: fp}
d := assigngraph.EntryDigest(e)
raw, _ := json.Marshal(e)
objects[assigngraph.EntryObject(d)] = raw
return d
}
shared, old, running, cand := entry("a", "fp-a"), entry("b", "fp-b1"), entry("c", "fp-c1"), entry("d", "fp-d2")
revision := func(n int64, digests ...string) {
rev := meshwants.AssignmentRevision{Revision: n}
for _, d := range digests {
rev.Entries = append(rev.Entries, meshwants.NodeEntryRef{Node: "n1", Digest: d})
}
raw, _ := json.Marshal(rev)
objects[assigngraph.TrunkObject(n)] = raw
}
candRaw, _ := json.Marshal(meshwants.AssignmentRevision{Revision: 1, Kind: "candidate", Group: "run-7", Heads: "h1",
Entries: []meshwants.NodeEntryRef{{Node: "n1", Module: "d", Digest: cand}}})
objects[assigngraph.CandidateObject("run-7", "h1")] = candRaw
revision(1, shared, old, running)
revision(2, shared, old)
revision(3, shared)
k := &revisionRemover{ctx: context.Background(), objects: objects, logf: t.Logf,
inUse: func(module, fp string) bool { return module == "c" && fp == "fp-c1" }}
k.judge()
has := func(name string) bool { _, ok := objects[name]; return ok }
for name, want := range map[string]bool{assigngraph.TrunkObject(1): false, assigngraph.TrunkObject(2): false, assigngraph.TrunkObject(3): true,
assigngraph.EntryObject(old): false, assigngraph.EntryObject(running): true, assigngraph.EntryObject(shared): true,
assigngraph.EntryObject(cand): true, assigngraph.CandidateObject("run-7", "h1"): true} {
if has(name) != want {
t.Errorf("%s kept = %v, want %v", name, has(name), want)
}
}
}
@@ -17,7 +17,6 @@ import (
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
mdcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient"
mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
"github.com/nats-io/nats.go"
@@ -341,11 +340,11 @@ func (p *passer) stepProposal(ctx context.Context, prop mma.Proposal, rev uint64
}
prop.Verdict = &v
switch v.State {
case mdcc.VerdictFail:
case plc.VerdictFail:
prop.State, prop.Ask = mmac.ProposalFailed, ""
case plc.VerdictWaits:
prop.State, prop.Ask = mmac.ProposalAnswering, ""
case mdcc.VerdictPass:
case plc.VerdictPass:
if prop.State != mmac.ProposalAsked || again {
// A proposal none of whose changes the setting ask-operator-for names is applied at once, with no ask (A-425a).
if kinds := proposalKinds(prop, v); !p.asksFor(kinds) {
@@ -312,10 +312,10 @@ func warrantOf(v any) (*mma.Warrant, error) {
// mesh-node-enroller when the proven caller is that module's (its bus user `<node>.<module>`, never a person's
// `person.<module>`), else the caller as proven, which the refusal names.
func moduleOfCaller(by string, enrollers []string) string {
for _, module := range enrollers {
if (stdio.Callers{module}).Allows(by) {
return module
}
// The enrolment's caller stays (design 47 H-A-41): a module's bus user is `<node>.<module>`, a person's `person.<name>`.
_, module, ok := strings.Cut(by, ".")
if ok && !strings.HasPrefix(by, "person.") && slices.Contains(enrollers, module) {
return module
}
return by
}
@@ -20,11 +20,9 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/seatlist"
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/provisioning/go/clients/meshprovisionerclient"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/views"
@@ -270,19 +268,6 @@ func TestTheSeatsVerbs(t *testing.T) {
})
}
s.seatList = nil
t.Run("1966: the seat list's again tool answers an operator's session through the mesh MCP server", func(t *testing.T) {
// Such a session is proved as its machine's tool runner (issue 627); the healers too, no other module. The list names
// the seats, resolved from the assigner's own seat-holders (A-295, A-298): a module holding neither is refused.
held := map[string][]byte{"node-tool-runner.shanks": []byte(`{"holders":[{"module":"node-tools","node":"shanks"}]}`),
"mesh-healers": []byte(`{"holders":[{"module":"mesh-delivery-watchman","node":"ace"}]}`)}
holders := seatlist.HoldersIn(func() (map[string][]byte, error) { return held, nil })
for caller, refused := range map[string]bool{"person.jochen": false, "shanks.node-tools": false, "ace.mesh-delivery-watchman": false,
"ace.mesh-healers": true, "ace.messenger": true} {
if err := seatlist.RefusalWith("assigner_seat_list_again", seatListAgainCallers, caller, holders); (err != nil) != refused {
t.Errorf("%s: refused=%v, err %v", caller, refused, err)
}
}
})
t.Run("1953/D4-D6: the seat mesh-wants' upgrade and bus", wantsVerbs)
t.Run("1955/L7 (ADR 0571 §6): rule 7 reads the node's own composition; an unplaced node is said", func(t *testing.T) {
w := newWorld()
@@ -533,51 +518,6 @@ func TestTheSeatsVerbs(t *testing.T) {
})
}
})
t.Run("1954/D1: a failed provision is the assigner's finding until it is provided", func(t *testing.T) {
findings := map[string][]byte{}
p := &passer{w: newWorld(), logf: func(string, ...any) {}, kvs: kvSet{buckets.Provisions: nil}, findings: assign.Findings{
Put: putInto(findings),
Delete: func(k string) error { delete(findings, k); return nil }}}
failed, _ := meshprovisionerclient.Encode(meshprovisionerclient.Provision{Provision: "db", Consumer: meshprovisionerclient.End{Module: "photos", Node: "ace"},
Provider: meshprovisionerclient.End{Module: "postgres", Node: "novox"}, State: meshprovisionerclient.Failed, Why: "the role exists already"})
p.w.putEntry(buckets.Provisions, "ace.photos.db", failed, 1, time.Now())
p.kvs[buckets.Provisions] = &memKV{}
of := p.provisionsOf()
if got := of("photos")("ace"); got["ace.photos.db"].State != meshprovisionerclient.Failed {
t.Fatalf("provisions = %+v", got)
}
if _, ok := findings[assign.ProvisionFailedKey("ace.photos.db")]; !ok || len(findings) != 1 {
t.Fatalf("findings = %v", findings)
}
provided, _ := meshprovisionerclient.Encode(meshprovisionerclient.Provision{Provision: "db", Consumer: meshprovisionerclient.End{Module: "photos", Node: "ace"},
Provider: meshprovisionerclient.End{Module: "postgres", Node: "novox"}, State: meshprovisionerclient.Provided})
p.w.putEntry(buckets.Provisions, "ace.photos.db", provided, 2, time.Now())
p.provisionsOf()
if len(findings) != 0 {
t.Errorf("findings after provided = %v", findings)
}
// A required provision with no key: pulsed with the bound first, said once the pulse expired, ended once keyed.
ctx := context.Background()
p.kvs[plc.PulsesBucket()] = &memKV{values: map[string][]byte{}}
gone := map[string]bool{"ace.photos.s3": true}
p.provisionsMissing(ctx, gone)
if !p.pulsing("provision-missing.ace.photos.s3") || len(findings) != 0 {
t.Fatalf("first seen: pulsing %v, findings %v", p.pulsing("provision-missing.ace.photos.s3"), findings)
}
p.provisionsMissing(ctx, gone)
if len(findings) != 0 {
t.Fatal("said before its bound")
}
p.w.put(plc.PulsesBucket(), "provision-missing.ace.photos.s3", nil) // the server expired it
p.provisionsMissing(ctx, gone)
if _, ok := findings[assign.ProvisionMissingKey("ace.photos.s3")]; !ok {
t.Fatalf("past its bound: findings %v", findings)
}
p.provisionsMissing(ctx, map[string]bool{})
if len(findings) != 0 {
t.Errorf("keyed again: findings %v", findings)
}
})
// A whole state is read in pages where the store has them, never a key at a time (27 s for the assignments live,
// 2026-11-14): the paged read answers what the key-by-key read answers, and asks no key alone.
direct, err := readAll(st, haveState)
@@ -1,16 +1,7 @@
package main
import (
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The assigner reads the seat list as every part does, through mesh-sdk's one wiring (go/seatlist.Part; design 47 G §204): its
// reader over the seat mesh-catalog's verb seat-definitions and its two events, its tools `assigner_seat_list` and
// `assigner_seat_list_again`. What the reader holds is given to catalogue at every change, which the check of a proposal and the
// seat-holders state read; until the list is read, a mesh seat the bootstrapped definitions do not name is never judged held once
// (plc.CheckAssignments), and seat-holders is not written.
// A call through the mesh MCP server is proved only as its machine's tool runner (issue 627), so the holders of the seat
// node-tool-runner stand for an operator's session until a session is proved (issue 1966). The list names seats, never a
// module, resolved from the assigner's own seat-holders (design 47 G A-210, A-295, A-298).
var seatListAgainCallers = []string{stdio.AnyPerson, stdio.CallerSeatPrefix + "node-tool-runner", stdio.CallerSeatPrefix + "mesh-healers"}
@@ -60,7 +60,7 @@ func gateOver(t *testing.T, silent bool) *seatlist.Part {
// that waits for it to stay unread keeps short.
t.Cleanup(busretry.Waits(20*time.Millisecond, time.Millisecond, 5*time.Millisecond))
}
g := seatlist.NewPart("assigner", seatListAgainCallers)
g := seatlist.NewPart("assigner")
r := g.Follow(standInCatalog{silent: silent}, nil, t.Logf)
if r == nil {
t.Fatal("the reader did not start")
@@ -98,7 +98,7 @@ func TestTheSeatListIsWiredByTheSDKAlone(t *testing.T) {
// A-179, A-186: the definition the verb input's callers are checked against is the seat list's, none before the reader starts
// or while the seat mesh-catalog has not answered, and none for a seat the list does not hold.
func TestTheAnsweredSeatsDefinitionIsTheSeatListsOnceRead(t *testing.T) {
if _, ok := seatlist.Definition(seatlist.NewPart("assigner", seatListAgainCallers).Reader, "mesh-wants")(); ok {
if _, ok := seatlist.Definition(seatlist.NewPart("assigner").Reader, "mesh-wants")(); ok {
t.Error("a definition is answered before the seat list's reader started")
}
if _, ok := seatlist.Definition(gateOver(t, true).Reader, "mesh-wants")(); ok {
@@ -0,0 +1,308 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-assigner/internal/assign"
)
// One pipeline's wants are written tier by tier (design 47 H §751, H-A-10, H-A-56): on a passed pipeline-ended the assigner
// writes the wants of its first tier's movers; once each of them runs at the mover's fingerprint (the node-engine seat's
// `running`, H-A-40) on every present placing machine, it writes the next tier's, and so on. The tier progress is the key
// `pipeline.<branch>.<source>` of the state written, `{tier, since, movers}`; a tier counts placed movers only, and a machine away
// is not waited for. A tier whose movers do not all run within `tier-bound` ends the delivery loudly: no later tier is written,
// the finding `tier-late` (scope delivery, id the pipeline) is raised naming the movers and machines not running, and
// `pipeline-wanted` says outcome tier-late; once every tier runs it says outcome running and the key goes (H-A-75). tier-late
// clears when the late movers run or a later passed pipeline moves them (H-A-56).
// tierPrefix starts the key of a pipeline's tier progress in the state written.
const tierPrefix = "pipeline."
// kindTierLate is the finding of a tier not running within tier-bound (design 47 H §751).
const kindTierLate = "tier-late"
// defaultTierBound is tier-bound's default, 30 minutes (design 47 H §751).
const defaultTierBound = 30 * time.Minute
// tierMover is one mover of a passed pipeline whose version the state written keeps: its module, fingerprint and tier.
type tierMover struct {
Module string `json:"module"`
Fp string `json:"fp"`
Tier int64 `json:"tier"`
}
// tierProgress is a pipeline's tier progress (H-A-56): the tier whose wants are written, since when, and the movers.
type tierProgress struct {
Tier int64 `json:"tier"`
Since time.Time `json:"since"`
Movers []tierMover `json:"movers"`
}
// 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 }
// isTierKey says whether a key of the state written is a pipeline's tier progress: three parts, the first `pipeline` (a module's
// end has two).
func isTierKey(key string) bool {
return strings.HasPrefix(key, tierPrefix) && strings.Count(key, ".") == 2
}
// startTiers writes the tier progress of a passed pipeline whose movers' versions are now kept, its first tier the lowest of
// theirs, since now. A pipeline heard again writes nothing.
func (e *pipelineEnds) startTiers(pipeline string, movers []tierMover) error {
if len(movers) == 0 {
return nil
}
first := movers[0].Tier
for _, m := range movers {
first = min(first, m.Tier)
}
value, err := json.Marshal(tierProgress{Tier: first, Since: e.clock().UTC(), Movers: movers})
if err != nil {
return err
}
if err := e.st.swap(tierKey(pipeline), value, 0); err != nil && !errors.Is(err, errSwapped) {
return err
}
return nil
}
func (e *pipelineEnds) clock() time.Time {
if e.now != nil {
return e.now()
}
return time.Now()
}
// tiersOf is the tier progress of pipeline, with its revision; false when none stands.
func (e *pipelineEnds) tiersOf(pipeline string) (tierProgress, uint64, bool) {
raw, rev, err := e.st.get(tierKey(pipeline))
var t tierProgress
if err != nil || raw == nil || json.Unmarshal(raw, &t) != nil {
return tierProgress{}, 0, false
}
return t, rev, true
}
// tierWritten says whether the want of an end may be written: its pipeline's tier progress reached the end's rank, or no
// progress stands for its pipeline (every tier ran).
func (e *pipelineEnds) tierWritten(end End) bool {
t, _, ok := e.tiersOf(end.Pipeline)
return !ok || end.Rank <= t.Tier
}
// tierBound is the setting tier-bound; zero or less is its default.
func (p *passer) tierBoundOf() time.Duration {
if p.tierBound > 0 {
return p.tierBound
}
return defaultTierBound
}
// tiers moves each pipeline's tier progress (design 47 H §751): a tier whose placed movers all run on every present placing machine
// gives way to the next, the last to the end said `running`; a tier past tier-bound is late. placedOn is, by module, the nodes
// placing it on branch. It returns the earliest deadline still to come (zero: none), for one timer to wake the pass at.
func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []string) time.Time {
if p.ends == nil {
return time.Time{}
}
ks, err := p.ends.st.keys()
if err != nil {
p.logf("the tier progress cannot be listed: %v", err)
return time.Time{}
}
sort.Strings(ks)
now := p.clock().UTC()
bound := p.tierBoundOf()
var next time.Time
for _, key := range ks {
if !isTierKey(key) {
continue
}
pipeline := strings.TrimPrefix(key, tierPrefix)
branchEsc, source, _ := strings.Cut(pipeline, ".")
branch, err := keys.UnescapeName(branchEsc)
if err != nil {
continue
}
for {
t, rev, ok := p.ends.tiersOf(pipeline)
if !ok {
break
}
notRunning := p.notRunning(n, placedOn, pipeline, branch, t, t.Tier)
late := !now.Before(t.Since.Add(bound))
if late {
p.tierLate(pipeline, branch, source, t, notRunning)
break
}
if len(notRunning) > 0 {
if d := t.Since.Add(bound); next.IsZero() || d.Before(next) {
next = d
}
break
}
// The tier runs: the next tier's wants are written, or every tier ran.
later := int64(0)
for _, m := range t.Movers {
if m.Tier > t.Tier && (later == 0 || m.Tier < later) {
later = m.Tier
}
}
if later == 0 {
if err := p.ends.st.drop(key); err != nil {
p.logf("the tier progress %s is not deleted: %v", key, err)
break
}
p.sayPipelineWanted(pipeline, branch, source, meshwants.PipelineWantedOutcomeRunning, nil)
break
}
value, err := json.Marshal(tierProgress{Tier: later, Since: now, Movers: t.Movers})
if err == nil {
err = p.ends.st.swap(key, value, rev)
}
if errors.Is(err, errSwapped) {
continue
}
if err != nil {
p.logf("the tier progress %s is not moved to tier %d: %v", key, later, err)
break
}
p.logf("pipeline %s: tier %d runs on every present placing machine, so tier %d's wants are written", pipeline, t.Tier, later)
}
}
return next
}
// notRunning is, of tier's movers in t whose kept end still names pipeline, those not running at their fingerprint on a present
// placing machine, with those machines. A mover a later pipeline moved counts as run; one placed nowhere counts as run.
func (p *passer) notRunning(n assign.Nodes, placedOn func(module, branch string) []string, pipeline, branch string, t tierProgress, tier int64) []meshwants.NotRunning {
var out []meshwants.NotRunning
for _, m := range t.Movers {
if m.Tier != tier {
continue
}
if end, ok := p.ends.endOf(m.Module, branch); !ok || end.Pipeline != pipeline {
continue // a later pipeline moved it
}
var machines []string
for _, node := range placedOn(m.Module, branch) {
if online, known := n.Online[node]; known && !online {
continue // a machine away is not waited for
}
r, ok := n.Running[node][m.Module]
if !ok || r.Stopped || r.Fingerprint != m.Fp {
machines = append(machines, node)
}
}
if len(machines) > 0 {
sort.Strings(machines)
out = append(out, meshwants.NotRunning{Module: m.Module, Machines: machines})
}
}
return out
}
// tierLate ends a pipeline's delivery at a tier past tier-bound: the finding tier-late is raised and pipeline-wanted says tier-late,
// once each; the finding clears once the late movers run or a later pipeline moved them. The progress stays, so no later tier is
// written, until no later tier's mover is kept at this pipeline any more.
func (p *passer) tierLate(pipeline, branch, source string, t tierProgress, notRunning []meshwants.NotRunning) {
o := tierLateFinding(pipeline, t.Tier, notRunning)
key := views.FindingKey(o.Scope, assign.KeyID(o.ID), o.Kind)
if len(notRunning) > 0 {
if !p.said[key+".raised"] {
if p.findings.Put != nil {
if err := p.findings.Put(o.Finding(p.clock())); err != nil {
p.logf("the finding %s is not written: %v", key, err)
return
}
}
p.said[key+".raised"] = true
delete(p.said, key+".cleared")
p.logf("pipeline %s: tier %d is late (tier-bound %s): %s; no later tier is written", pipeline, t.Tier, p.tierBoundOf(), o.Summary)
p.sayPipelineWanted(pipeline, branch, source, meshwants.PipelineWantedOutcomeTierLate, notRunning)
}
} else if !p.said[key+".cleared"] {
if p.findings.Delete != nil {
if err := p.findings.Delete(key); err != nil {
p.logf("the finding %s is not deleted: %v", key, err)
return
}
}
p.said[key+".cleared"] = true
delete(p.said, key+".raised")
}
for _, m := range t.Movers {
if m.Tier <= t.Tier {
continue
}
if end, ok := p.ends.endOf(m.Module, branch); ok && end.Pipeline == pipeline {
return // a later tier's mover still kept at this pipeline: its want stays unwritten
}
}
if len(notRunning) == 0 {
if err := p.ends.st.drop(tierKey(pipeline)); err != nil {
p.logf("the tier progress of %s is not deleted: %v", pipeline, err)
}
}
}
// tierLateFinding is the finding tier-late of pipeline's tier, naming the movers and machines not running (design 47 H §751).
func tierLateFinding(pipeline string, tier int64, notRunning []meshwants.NotRunning) assign.Observed {
var named []string
for _, nr := range notRunning {
named = append(named, fmt.Sprintf("%s on %s", nr.Module, strings.Join(nr.Machines, ", ")))
}
summary := fmt.Sprintf("pipeline %s: tier %d does not run within tier-bound: %s", pipeline, tier, strings.Join(named, "; "))
return assign.Observed{Scope: mcc.ScopeDelivery, ID: pipeline, Kind: kindTierLate, Severity: mcseat.FindingSeverityWarning,
Summary: summary, Headline: "A delivery's tier does not run in time",
Explanation: summary + ". The assigner writes no later tier of this pipeline; the delivery ends here.",
Source: "assigner." + kindTierLate}
}
// sayPipelineWanted says the seat mesh-wants' pipeline-wanted of pipeline, once (its id the pipeline and the outcome).
func (p *passer) sayPipelineWanted(pipeline, branch, source, outcome string, notRunning []meshwants.NotRunning) {
var src int64
_, _ = fmt.Sscan(source, &src)
body := meshwants.PipelineWantedEvent{V: keys.Version, Pipeline: pipeline, Branch: branch, Source: src, Outcome: outcome, NotRunning: notRunning}
event := meshwants.EventPipelineWanted + "." + pipeline
if err := p.wantsSay(event, body, "pipeline-wanted."+pipeline+"."+outcome); err != nil {
p.logf("pipeline-wanted of %s is not said: %v", pipeline, err)
}
}
// tierDeadline sets the one timer that wakes the pass at the earliest tier's deadline (H-A-56); zero stops it.
func (p *passer) tierDeadline(at time.Time) {
if p.tierWake == nil {
return
}
if p.tierTimer != nil {
p.tierTimer.Stop()
}
if at.IsZero() {
return
}
p.tierTimer = time.AfterFunc(max(at.Sub(p.clock()), 0), p.tierWake)
}
// tierBoundSetting is the setting tier-bound in minutes (design 47 H §751), read at the start from the file the manifest declares
// with the content ${config:tier-bound}; zero, its default, for a file missing or empty.
func tierBoundSetting(getenv func(string) string) (time.Duration, error) {
minutes, err := settingFile(getenv("MESH_ASSIGNER_TIER_BOUND_FILE"))
return time.Duration(minutes) * tierBoundUnit, err
}
// tierBoundUnit is the unit of the setting tier-bound, a minute; the whole test sets a shorter one, so a tier passes its bound
// without a test waiting minutes.
var tierBoundUnit = time.Minute
@@ -0,0 +1,118 @@
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
"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"
"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"
"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/views"
"mesh-delivery-assigner/internal/assign"
"mesh-delivery-assigner/internal/buckets"
)
// A7/AC1, A7/AC2 (design 47 H §751, H-A-56): a pipeline of a provider (tier 1) and its consumer (tier 2) writes the provider's
// wants first and the consumer's only once the provider runs at its fingerprint on every present placing machine (one machine
// away is not waited for), then says pipeline-wanted running and drops its progress; a provider that never runs is late at
// 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) {
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
for _, runs := range []bool{true, false} {
start := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC)
now := start
wantsKV := &memKV{values: map[string][]byte{}}
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, start)
p.now = func() time.Time { return now }
p.say = func(oc.Condition) error { return nil }
findings := map[string]mcseat.Finding{}
p.findings = assign.Findings{Put: func(f mcseat.Finding) error { findings[views.FindingKey(f.Scope, f.ID, f.Kind)] = f; return nil },
Delete: func(key string) error { delete(findings, key); return nil }}
var said []meshwants.PipelineWanted
p.publishWants = func(event string, body any, _ string) error {
if b, ok := body.(meshwants.PipelineWantedEvent); ok {
if event != "pipeline-wanted."+trunkBranch+".5" {
t.Errorf("pipeline-wanted said as %s", event)
}
said = append(said, b)
}
return nil
}
for i, m := range []struct{ name, fp string }{{"db", db}, {"web", web}} {
digest := strings.Repeat(string(rune('e'+i)), 64)
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: m.fp, Manifest: digest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
putModuleRaw(p.w, trunkBranch, m.name, mod)
p.w.manifests[digest] = parsed{module: m.name, manifest: catalogue.Manifest{Module: m.name}}
}
placeOn(t, p.w, "g14", "db", "web")
placeOn(t, p.w, "ace", "db", "web")
p.w.heardPresence("ace", true, start) // away: not waited for
p.w.mu.Lock()
p.w.runningHeard = true
p.w.mu.Unlock()
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
p.ends.trunk, p.ends.now = p.w.trunkName, func() time.Time { return now }
if _, err := p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("db", db, "0.2.0", 1, mpr.StepResultOutcomePassed),
mover("web", web, "0.1.2", 2, mpr.StepResultOutcomePassed))); err != nil {
t.Fatal(err)
}
wanted := func(node, module string) bool {
key, _ := mwc.WantKey(node, module)
_, ok := wantsKV.values[key]
return ok
}
p.wants(context.Background())
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)
}
if runs {
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db})
if err := p.w.hearRunning("running.g14.db", raw); err != nil {
t.Fatal(err)
}
now = start.Add(time.Minute)
p.wants(context.Background())
if !wanted("g14", "web") || !wanted("ace", "web") {
t.Fatalf("the consumer's want is not written once its provider runs: %v", wantsKV.values)
}
raw, _ = json.Marshal(nodeengine.Running{Node: "g14", Module: "web", Fingerprint: web})
_ = p.w.hearRunning("running.g14.web", raw)
p.wants(context.Background())
if len(said) != 1 || said[0].Outcome != meshwants.PipelineWantedOutcomeRunning || len(findings) != 0 {
t.Errorf("every tier runs: said %+v, findings %v", said, findings)
}
if _, _, ok := p.ends.tiersOf(trunkBranch + ".5"); ok {
t.Error("the tier progress stands after every tier ran")
}
continue
}
now = start.Add(29 * time.Minute)
p.wants(context.Background())
if len(findings) != 0 || len(said) != 0 {
t.Fatalf("late before tier-bound: %v, %+v", findings, said)
}
now = start.Add(30 * time.Minute)
p.wants(context.Background())
p.wants(context.Background())
f, ok := findings["delivery."+assign.KeyID(trunkBranch+".5")+".tier-late"]
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)
}
if len(said) != 1 || said[0].Outcome != meshwants.PipelineWantedOutcomeTierLate || len(said[0].NotRunning) != 1 || said[0].NotRunning[0].Module != "db" {
t.Errorf("pipeline-wanted tier-late is not said once: %+v", said)
}
if wanted("g14", "web") || wanted("ace", "web") {
t.Error("a consumer's want is written after its provider's tier was late")
}
}
}
@@ -1,7 +1,6 @@
package main
import (
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
plc "mesh-delivery-assigner/internal/assignment"
"encoding/json"
@@ -22,13 +21,10 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/seatlist"
"git.novox.be/novox/mesh-sdk/go/stateobjects"
"mesh-delivery-assigner/internal/buckets"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient/enginereads"
)
// The assigner's tools (novox/hq ADR 0546), served through the tool runner from its bundle: a process never serves (ADR
@@ -36,9 +32,6 @@ import (
// every step as the event put. They are the module's own tools; the seat mesh-module-assigner's verbs are served beside them
// (seat_tools.go, ADR 0567 §10).
// engineReadsTool lists what each node's engine reads, as the assigner uses it, and asks one node's engine again.
const engineReadsTool = "assigner_engine_reads"
// putsState is the assigner's state of puts, as the runtime names a module's own state.
const putsState = "puts"
@@ -215,12 +208,6 @@ func (s *putTools) doRelease(args map[string]any, by string) (any, error) {
if arg(args, "how") != "" {
return s.doReleaseWait(args, by) // a wait on an outside cause (outside_tools.go, design 47 G §706)
}
if step := arg(args, "step"); step != "" {
if step != meshwants.WaitStepDelivery {
return nil, fmt.Errorf("step is %s, the one wait released by its step, not %q", meshwants.WaitStepDelivery, step)
}
return s.doReleaseDelivery(args, by) // a dependent's delivery wait (delivered.go, design 47 G §376, A-246)
}
node, module, why := arg(args, "node"), arg(args, "module"), arg(args, "why")
key, err := puts.Key(node, module)
if err != nil {
@@ -353,12 +340,10 @@ func (s *putTools) tools() []stdio.Tool {
"rules write the machine's want again from their next pass. Nothing changes on the machine until they move it.",
Input: schema(map[string]string{"node": "the machine", "module": "the module", "why": "why, kept with the put",
"how": "with how, the wait of the delivery on an outside cause (assigner_waits) is released, not a put: go-on (the module counts healthy there), " +
"failed (the failing check is the delivery's), rejudge (judge it again now), or now (the entry waiting for an acting part's new version moves with the running one); written in the hand-act log first",
"step": "delivery: the module's wait for its dependency's delivery (assigner_waits) is released, its want written now; no machine is named; written in the hand-act log first"},
"failed (the failing check is the delivery's), or rejudge (judge it again now); written in the hand-act log first"},
[]string{"module", "why"}),
Run: func(a map[string]any) (any, error) { return s.doRelease(a, stdio.CallerOf(a)) }},
s.waitsTool(),
s.deliveredAgainTool(),
{Name: toolPuts, Description: "Every put and where it stands (novox/hq ADR 0546): its version, hold, why, each step with " +
"its time and words. Narrowed by machine or module. Read-only.",
Input: schema(map[string]string{"node": "one machine", "module": "one module"}, nil),
@@ -403,7 +388,7 @@ func serveTools() error {
}
}()
// The seat list (seatlist.go), read through the runtime once Serve has its channel: the seat's verbs judge by it.
gate := seatlist.NewPart("assigner", seatListAgainCallers)
gate := seatlist.NewPart("assigner")
go func() {
<-stdio.Served()
gate.Follow(seatlist.StdioBus(), nil, func(f string, a ...any) { fmt.Fprintf(os.Stderr, "mesh-delivery-assigner: "+f+"\n", a...) })
@@ -417,8 +402,6 @@ func serveTools() error {
return stdio.SeatPublish(wantsEventSubject(e), b, id)
})
wants.watched = stdio.NewWatchedStates() // the large states read whole from one watched copy (ADR 0580 clause 3)
// The callers' seat entries are resolved from the assigner's own seat-holders, its watched copy (A-298).
gate.Holders(seatlist.HoldersIn(func() (map[string][]byte, error) { return wants.watched.Values(mma.StateSeatHolders) }))
// The verb assignments with seats answers from the same watched copy, so every caller of it is fast too (issue 1982).
seatVerbs.watched = wants.watched
wants.revisions = runtimeObjects{busstate.ObjectsOf(assigngraph.RevisionsObjects)}
@@ -427,12 +410,12 @@ func serveTools() error {
tools = append(tools, inputsRead(keeper), inputsDrop(keeper, stdio.Ask))
tools = append(tools, compositionsTools(stdio.Ask)...) // the composition runs' read and drop, through their verbs (§728)
tools = append(tools, viewTools(os.Getenv, keptSource, time.Now)...)
// What each node's engine reads, as the assigner uses it (ADR 0618 §3): its own state engine-reads, asked again through it.
tools = append(tools, enginereads.Tool(engineReadsTool, "the assigner", enginereads.KeptState(stdio.State(engineReadsState)), false, time.Now))
// What each node's engine reads, as the assigner uses it: its own state engine-reads (design 47 H-A-104).
tools = append(tools, engineReadsTools(runtimeStore{})...)
tools = append(tools, writtenTools(runtimeStore{})...)
tools = append(tools, whyTools(runtimeStore{})...)
tools = append(tools, pinsTools(runtimeStore{}, stdio.Ask)...)
tools = append(tools, askAgainTools(runtimeStore{}, stdio.Ask, time.Now)...)
tools = append(tools, wantDropTools(runtimeStore{}, stdio.Ask)...)
return stdio.Serve("", tools)
}
@@ -0,0 +1,381 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph"
)
// The step validate (design 47 H §745; H-A-34, H-A-51, H-A-108): the assigner serves it as an accepted kind `step` of the seat
// mesh-wants, asked by the runner for each mover before its composition step. One run per take-in revision, a key
// `<pipeline>.validate` of the state composition-runs in the CompositionRun form with no machine, which every mover's step
// reads: the cycle the revision's entries make (graph.RefusedCycle) ends it at once; else the manifest validator built from
// the revision's own entry of the module holding the seat mesh-catalog, on the Go build seat as the composer is, runs in the
// sandbox over the revision's manifests and its base's (H-A-154), its input kept and served on mesh-wants' input.
// Every mover's step ends the same: failed `cycle` naming the cycle, failed `manifest-refused` naming every problem of a
// manifest the revision alters or between manifests one it alters takes part in, or passed.
const (
// validatorPackage is the manifest validator's import path in the module holding the seat mesh-catalog (the indexer's
// cmd/mesh-judge, design 47 H-A-34).
validatorPackage = "mesh-delivery-indexer/cmd/mesh-judge"
// validateKeySuffix ends the key of a revision's validate run, `<pipeline>.validate` (H-A-108).
validateKeySuffix = "." + meshwants.StepRunStepValidate
// beforeCase is the validator's case of the revision's base, beside changeCase (H-A-108 (3), H-A-151, H-A-154).
beforeCase = "before"
// The reasons a validate step fails with, the first word of its said (§745).
reasonManifestRefused = "manifest-refused"
reasonCycle = "cycle"
// betweenManifests is the validator's name for what it judges between manifests (the catalogue as a whole).
betweenManifests = "(between manifests)"
)
// validateKeyOf is the key of the validate run of the step's take-in revision.
func validateKeyOf(step meshwants.StepRun) (string, error) {
if step.Pipeline == "" {
return "", errors.New("the step names no pipeline, so no validate run is named")
}
return step.Pipeline + validateKeySuffix, nil
}
// isValidateRun says whether a run of the state is a revision's validate run: one with no machine.
func isValidateRun(run meshwants.CompositionRun) bool { return run.Machine == "" }
// validate runs one mover's validate step: it joins or starts the revision's validate run and judges the step from its end.
func (r *compositionRun) validate(ctx context.Context, id string, step meshwants.StepRun) stepOutcome {
key, err := validateKeyOf(step)
if err != nil {
return couldNotRun(err.Error())
}
candidate, err := candidateKeyOf(step)
if err != nil {
return couldNotRun(err.Error())
}
j, err := r.runs.joinAt(key, readerOf(id, step), candidate, "", buildstep.NewID())
if err != nil {
return couldNotRun("the validate run " + key + " is not joined: " + err.Error())
}
if j.started {
go r.startValidate(ctx, key, j.run, step)
}
return r.readValidate(ctx, key, step)
}
// resumeValidate judges a validate step taken up at the assigner's start from its revision's run.
func (r *compositionRun) resumeValidate(ctx context.Context, _ string, step meshwants.StepRun) stepOutcome {
key, err := validateKeyOf(step)
if err != nil {
return couldNotRun(err.Error())
}
return r.readValidate(ctx, key, step)
}
// 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 {
setShared(ctx, r.runs.sharedOf([]string{key}, nil))
setPhase(ctx, meshwants.StepProgressEventPhaseRun)
run := r.runs.await(ctx, []string{key})[key]
setPhase(ctx, meshwants.StepProgressEventPhaseReport)
out := r.judgeValidate(ctx, step, run)
out.Shared = r.runs.sharedOf([]string{key}, map[string]meshwants.CompositionRun{key: run})
return out
}
// judgeValidate is a step's end from its revision's validate run: could not run with the run's words; failed `cycle` naming
// the cycle; failed `manifest-refused` naming every problem the revision causes; else passed.
func (r *compositionRun) judgeValidate(ctx context.Context, step meshwants.StepRun, run meshwants.CompositionRun) stepOutcome {
if run.Ended == nil {
return couldNotRun("the step stopped before its validate run ended")
}
if run.Outcome != meshwants.CompositionRunOutcomePassed {
return couldNotRun(run.Said)
}
var v validateVerdict
if raw, err := json.Marshal(run.Verdict); err != nil || json.Unmarshal(raw, &v) != nil {
return couldNotRun("the validate run's verdict does not read")
}
if len(v.Cycle) > 0 {
return stepOutcome{Outcome: meshwants.StepEndedOutcomeFailed, Said: reasonCycle + ": " + cycleWords(v.Cycle)}
}
half, err := r.revision(ctx, step)
if err != nil {
return couldNotRun("the step's catalog revision is not read: " + err.Error())
}
before, err := r.before(ctx, step, half)
if err != nil {
return couldNotRun("the base of the case before is not read: " + err.Error())
}
// A revision that names no base (the branch's first take-in) is judged against an empty case before, and says so (H-A-151).
empty := ""
if half.Revision.Base <= 0 {
empty = emptyBeforeWords
}
if problems := causedProblems(v.Change, v.Before, altered(half, before)); len(problems) > 0 {
said := reasonManifestRefused + ": " + strings.Join(problems, "; ")
if empty != "" {
said += " (" + empty + ")"
}
return stepOutcome{Outcome: meshwants.StepEndedOutcomeFailed, Said: said}
}
return stepOutcome{Outcome: meshwants.StepEndedOutcomePassed, Said: empty}
}
// emptyBeforeWords say, in a validate step's end, that its revision names no base: the branch's first take-in, judged against
// an empty case before (H-A-151, H-A-154).
const emptyBeforeWords = "the case before is empty: the revision names no base, the branch's first take-in"
// validateVerdict is a validate run's verdict as the run keeps it: the cycle the revision makes, or the validator's two cases.
type validateVerdict struct {
Cycle []meshcatalog.ArtifactRef `json:"cycle,omitempty"`
Change composer.CaseVerdict `json:"change"`
Before composer.CaseVerdict `json:"before"`
}
// asVerdict is v as a run's verdict.
func (v validateVerdict) asVerdict() (map[string]any, error) {
raw, err := json.Marshal(v)
if err != nil {
return nil, err
}
var out map[string]any
return out, json.Unmarshal(raw, &out)
}
// cycleWords names a cycle as the artifacts it passes through.
func cycleWords(cycle []meshcatalog.ArtifactRef) string {
words := make([]string, len(cycle))
for i, a := range cycle {
words[i] = string(a)
}
return strings.Join(words, " → ")
}
// before is the case before of the step's revision half: the revision its base names, the newest kept revision below it that
// its take-in pinned, read through the seat mesh-catalog's verb revision (H-A-108 (3), H-A-151, H-A-154); empty where the
// revision names no base, the branch's first take-in.
func (r *compositionRun) before(ctx context.Context, step meshwants.StepRun, half mcc.Half) (mcc.Half, error) {
if half.Revision.Base <= 0 {
return mcc.Half{Entries: map[string]meshcatalog.CatalogEntry{}}, nil
}
base := step
base.Revision = half.Revision.Base
return r.revision(ctx, base)
}
// altered are the modules whose manifest the revision adds or changes against the one before it.
func altered(half, before mcc.Half) []string {
var out []string
for name, e := range half.Entries {
if len(e.Manifest) == 0 {
continue
}
b, ok := before.Entries[name]
switch {
case !ok || len(b.Manifest) == 0:
out = append(out, name)
case e.ManifestDigest != "" && b.ManifestDigest != "":
if e.ManifestDigest != b.ManifestDigest {
out = append(out, name)
}
default:
x, _ := json.Marshal(e.Manifest)
y, _ := json.Marshal(b.Manifest)
if string(x) != string(y) {
out = append(out, name)
}
}
}
slices.Sort(out)
return out
}
// causedProblems are the problems the revision causes (ADR 0578 §2): every problem of a manifest it alters, and of any other
// manifest, or between manifests, each problem the case before did not have.
func causedProblems(change, before composer.CaseVerdict, touched []string) []string {
var out []string
for _, module := range slices.Sorted(maps.Keys(change.Manifests)) {
read := change.Manifests[module]
if read.Accepted || read.Refused == "" {
continue
}
had := map[string]bool{}
for _, p := range strings.Split(before.Manifests[module].Refused, "\n") {
had[p] = true
}
var caused []string
for _, p := range strings.Split(read.Refused, "\n") {
if p != "" && (slices.Contains(touched, module) || !had[p]) {
caused = append(caused, p)
}
}
if len(caused) == 0 {
continue
}
what := module
if module == betweenManifests {
what = "between manifests"
}
out = append(out, what+": "+strings.Join(caused, "; "))
}
return out
}
// catalogEntry is the entry of the module that holds the seat mesh-catalog, or false.
func catalogEntry(entries map[string]meshcatalog.CatalogEntry) (meshcatalog.CatalogEntry, bool) {
for _, name := range slices.Sorted(maps.Keys(entries)) {
for _, s := range entries[name].Serves {
if strings.HasPrefix(strings.TrimPrefix(s, "seat:"), meshcatalog.Seat+".") {
return entries[name], true
}
}
}
return meshcatalog.CatalogEntry{}, false
}
// manifestsOf are the half's manifests whole, as the validator's case holds them.
func manifestsOf(half mcc.Half) (map[string]composer.Manifest, error) {
out := map[string]composer.Manifest{}
for name, e := range half.Entries {
if len(e.Manifest) == 0 {
continue
}
raw, err := json.Marshal(e.Manifest)
if err != nil {
return nil, fmt.Errorf("the manifest of %s cannot be encoded: %w", name, err)
}
out[name] = composer.Manifest{Raw: raw}
}
return out, nil
}
// startValidate runs the validate run the step started: the revision's cycle ends it at once; else the validator's request
// is kept once in `inputs`, its program and input recorded on the run, and one run ask put on the Go build seat. A fault ends
// the run could not run.
func (r *compositionRun) startValidate(ctx context.Context, key string, run meshwants.CompositionRun, step meshwants.StepRun) {
ask := run.Ask
end := func(outcome, said string, verdict map[string]any) {
if _, err := r.runs.endRun(key, ask, outcome, said, verdict); err != nil {
r.logf("the validate run %s is not ended: %v", key, err)
}
}
couldNot := func(said string) { end(meshwants.CompositionRunOutcomeCouldNotRun, said, nil) }
half, err := r.revision(ctx, step)
if err != nil {
couldNot("the step's catalog revision is not read: " + err.Error())
return
}
if cycle := graph.RefusedCycle(half.Entries); cycle != nil {
verdict, err := validateVerdict{Cycle: cycle}.asVerdict()
if err != nil {
couldNot(err.Error())
return
}
end(meshwants.CompositionRunOutcomePassed, "", verdict)
return
}
before, err := r.before(ctx, step, half)
if err != nil {
couldNot("the base of the case before is not read: " + err.Error())
return
}
entry, ok := catalogEntry(half.Entries)
if !ok {
couldNot(fmt.Sprintf("the catalog revision %d holds no module claiming the seat %s, so no manifest validator is built", half.Revision.Revision, meshcatalog.Seat))
return
}
program, err := programOfEntry(entry)
if err != nil {
couldNot(err.Error())
return
}
program.Package = validatorPackage
seats, err := r.seats(ctx, half.Revision.Definitions)
if err != nil {
couldNot(err.Error())
return
}
change, err := manifestsOf(half)
if err != nil {
couldNot(err.Error())
return
}
prior, err := manifestsOf(before)
if err != nil {
couldNot(err.Error())
return
}
// No predefined key list and no known package names until a design line names the verb that gives them (H-A-108 (2)).
req := composer.Request{V: composer.Version, Cases: []composer.Case{{Name: changeCase, Manifests: change}, {Name: beforeCase, Manifests: prior}},
Seats: seats}
raw, err := json.Marshal(req)
if err != nil {
couldNot("its request cannot be encoded: " + err.Error())
return
}
digest, err := r.keeper.keep(ask, raw)
if err != nil {
couldNot("its request is not kept: " + err.Error())
return
}
ref, err := buildstep.RunInputOf(inputVerbKey, raw)
if err != nil {
couldNot(err.Error())
return
}
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
if c.Ask != ask || c.Ended != nil {
return false
}
c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: entry.Fp}
c.Input = digest
return true
}); err != nil {
couldNot("the run's program and input are not written: " + err.Error())
return
}
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}}
if err := r.put(ctx, a); err != nil {
couldNot("its run ask " + ask + " is not put: " + err.Error())
}
}
// validateRunVerdict reads the validator's answer: its two cases as the run keeps them, or why it is none.
func validateRunVerdict(answer []byte) (map[string]any, string) {
var v composer.Verdict
if err := json.Unmarshal(answer, &v); err != nil {
return nil, "the manifest validator answered no verdict: " + err.Error()
}
if v.V != composer.Version {
return nil, fmt.Sprintf("the manifest validator answered a verdict of version %d, the assigner reads %d", v.V, composer.Version)
}
var out validateVerdict
found := 0
for _, c := range v.Cases {
switch c.Name {
case changeCase:
out.Change, found = c, found+1
case beforeCase:
out.Before, found = c, found+1
}
}
if found != 2 {
return nil, "the manifest validator's verdict does not hold both the cases " + changeCase + " and " + beforeCase
}
verdict, err := out.asVerdict()
if err != nil {
return nil, "the manifest validator's verdict cannot be kept: " + err.Error()
}
return verdict, ""
}
@@ -0,0 +1,150 @@
package main
import (
"context"
"encoding/json"
"errors"
"strings"
"sync"
"testing"
"time"
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
)
// A10/AC1, A10/AC2 (design 47 H §745; H-A-34, H-A-51, H-A-108): every mover's validate step of one take-in reads one validate
// run, `<pipeline>.validate` of the state composition-runs; a manifest the revision alters that names an unknown field fails
// it `manifest-refused` naming the problem, a problem of a manifest it leaves as it was does not, and the validator is the
// revision's own entry of the module holding the seat mesh-catalog, on the Go build seat; a revision whose entries make a cycle
// fails it `cycle` naming the cycle, with no validator asked. The case before is the revision its base names (H-A-151, H-A-154:
// the newest kept below it, which the stand-in names as the indexer does); a revision naming no base, the branch's first take-in,
// is judged against an empty case before, said in its end, and no revision below it is asked.
func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
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"}
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}
}
revisions := map[int64][]meshcatalog.CatalogEntry{
6: {indexer, entry("web", "d-web-1"), entry("db", "d-db")},
7: {indexer, entry("web", "d-web-2"), entry("db", "d-db")},
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},
12: {indexer, entry("web", "d-web-2"), entry("db", "d-db")},
}
// 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).
base := func(n int64) (b int64) {
if n == 12 {
return 7
}
for k := range revisions {
if k < n && k > b {
b = k
}
}
return b
}
call := func(key string, body any) (json.RawMessage, error) {
raw, _ := json.Marshal(body)
switch key {
case mcc.RevisionVerb:
var in meshcatalog.RevisionInput
_ = json.Unmarshal(raw, &in)
entries, ok := revisions[in.Revision]
if !ok || in.Branch != "main" {
return nil, errors.New("asked another revision")
}
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{Revision: in.Revision, Base: base(in.Revision),
Definitions: []meshcatalog.CatalogRevisionDefinitionsItem{{Seat: "s1", Digest: "sd"}}}, Entries: entries})
case seatDefinitionsKey:
return json.Marshal(meshcatalog.SeatDefinitionsAnswer{Found: true, Entry: &meshcatalog.SeatDefinitionsAnswerEntry{Seat: "s1", Digest: "sd", Definition: map[string]any{"seat": "s1"}}})
}
return nil, errors.New("no such verb " + key)
}
var mu sync.Mutex
var asks []buildstep.StepAsk
var requests []composer.Request
keeper := testKeeper(&objectsMem{objs: map[string][]byte{}}, time.Now)
runs := newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf)
r := &compositionRun{runs: runs, keeper: keeper, reads: &compositionReads{}, call: call, now: time.Now, logf: t.Logf,
put: func(_ context.Context, a buildstep.StepAsk) error {
body, err := keeper.body(a.Run.Input.Digest)
if err != nil {
return err
}
req, err := composer.Decode(body)
if err != nil {
return err
}
mu.Lock()
asks, requests = append(asks, a), append(requests, req)
mu.Unlock()
answer, _ := json.Marshal(composer.Verdict{V: composer.Version, Cases: []composer.CaseVerdict{
{Name: changeCase, Manifests: map[string]composer.ManifestRead{"web": {Refused: `unknown field "colour"`}, "db": {Refused: "an old problem"}, "indexer": {Accepted: true}}},
{Name: beforeCase, Manifests: map[string]composer.ManifestRead{"db": {Refused: "an old problem"}}}}})
go func() {
if err := runs.heardEnd(buildstep.StepEnded{Asker: runAsker, Ask: a.ID, Outcome: buildstep.OutcomePassed, Node: "novox"},
func(buildstep.StepEnded) ([]byte, error) { return answer, nil }); err != nil {
t.Error(err)
}
}()
return nil
}}
steps := &compositionSteps{validate: r.validate, run: r.run}
if steps.howOf(meshwants.StepRunStepValidate, false) == nil || steps.howOf("check", false) != nil {
t.Error("the validate step is not taken, or another step is")
}
step := func(module string, revision int64) meshwants.StepRun {
return meshwants.StepRun{Step: meshwants.StepRunStepValidate, Pipeline: "main." + string(rune('0'+revision)), Branch: "main", Module: module,
Revision: revision, Source: revision}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
outs := make([]stepOutcome, 2)
var wg sync.WaitGroup
for i, module := range []string{"web", "db"} {
wg.Add(1)
go func() { defer wg.Done(); outs[i] = r.validate(ctx, "ask-"+module, step(module, 7)) }()
}
wg.Wait()
for i, o := range outs {
if o.Outcome != meshwants.StepEndedOutcomeFailed || !strings.HasPrefix(o.Said, reasonManifestRefused+": ") || !strings.Contains(o.Said, `web: unknown field "colour"`) ||
strings.Contains(o.Said, "an old problem") {
t.Errorf("mover %d's validate step ended %+v", i, o)
}
}
if len(asks) != 1 {
t.Fatalf("%d validator asks were put for one take-in, want 1", len(asks))
}
if p := asks[0].Run.Program; p.Commit != commitE3 || p.Dir != "modules/mesh-delivery-indexer" || p.Package != validatorPackage || len(asks[0].Run.Heads) != 0 {
t.Errorf("the validator is built from %+v", asks[0].Run)
}
if c := requests[0].Cases; len(c) != 2 || c[0].Name != changeCase || c[1].Name != beforeCase || len(c[1].Manifests) != 3 || requests[0].Predefined != nil || requests[0].Packages != nil {
t.Errorf("the validator's request is %+v", requests[0])
}
if _, _, ok, _ := runs.read("main.7" + validateKeySuffix); !ok {
t.Error("the validate run is not the key <pipeline>.validate of composition-runs")
}
o := r.validate(ctx, "ask-a", step("a", 9))
if o.Outcome != meshwants.StepEndedOutcomeFailed || o.Said != reasonCycle+": a:x → b:y → a:x" || len(asks) != 1 {
t.Errorf("a revision making a cycle ended %+v (%d validator asks)", o, len(asks))
}
// The stand-in validator answers its one verdict: judged against the empty case before, web's problem is the revision's.
if o := r.validate(ctx, "ask-first", step("indexer", 3)); o.Outcome != meshwants.StepEndedOutcomeFailed ||
o.Said != reasonManifestRefused+`: web: unknown field "colour" (`+emptyBeforeWords+")" || len(asks) != 2 || len(requests[1].Cases[1].Manifests) != 0 {
t.Errorf("a revision naming no base ended %+v (%d validator asks), want it judged against an empty case before, said", o, len(asks))
}
// Revision 12 holds revision 7's manifests and names base 7: judged against it, web's problem is the revision's, db's old one
// is not, and the case before holds base 7's manifests.
if o := r.validate(ctx, "ask-base", step("web", 12)); o.Outcome != meshwants.StepEndedOutcomeFailed ||
o.Said != reasonManifestRefused+`: web: unknown field "colour"` || len(asks) != 3 {
t.Errorf("a revision naming base 7 below its number ended %+v (%d validator asks), want it judged against base 7", o, len(asks))
} 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)
}
}
@@ -24,26 +24,6 @@ import (
// moduleGraph is the module graph of the catalog half of branch, from the entries' invokes and serves (design 47 G §184, §195).
func (p *passer) moduleGraph(branch string) graph.Graph { return p.w.graphOf(branch) }
// keptInvokes are the verbs of module the graph keeps as edges: each it invokes and does not leave out, that a module
// other than itself serves. A verb no module of the graph serves is no edge, so it holds nothing; nil when the graph holds
// no node of module.
func keptInvokes(g graph.Graph, module string) []string {
n, ok := g[module]
if !ok {
return nil
}
var out []string
for _, v := range n.Invokes {
if slices.Contains(n.LeftOut, v) {
continue
}
if slices.ContainsFunc(g.Servers(v), func(s string) bool { return s != module }) {
out = append(out, v)
}
}
return out
}
// served is, for this pass, whether a build serving a verb runs healthy on some node (graph.Served): every running healthy
// have's build (the builder's builds key of its module and fingerprint) names its manifest, and the verbs that manifest
// serves are served. A healthy build whose manifest cannot be read counts what the graph says its module serves, said in
@@ -73,7 +73,7 @@ func viewTools(getenv func(string) string, state func(string) views.Source, now
marks := state(views.MarksState)
var out []stdio.Tool
for _, t := range firstViewTools {
out = append(out, views.FirstViewTool(assignment.Module(), t.tool, t.state, t.words, views.ParseCallers(getenv(views.CallersEnv(t.tool))), state(t.state), marks, now))
out = append(out, views.FirstViewTool(assignment.Module(), t.tool, t.state, t.words, state(t.state), marks, now))
}
for _, t := range readTools {
out = append(out, views.ReadTool(assignment.Module(), t.tool, t.state, t.words, state(t.state), marks, now))
@@ -0,0 +1,146 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// wantDropTool drops one want of a node for a module by hand (design 47 H §765, H-A-58): a held or failed want of the earlier
// model goes at the clean state, its key deleted and the act written in the hand-act log; the next pass writes the want of the
// new form.
const wantDropTool = "assigner_want_drop"
// wantsState is the state the wants are kept in.
const wantsState = "wants"
// dropWant deletes the want of module on node, the act first recorded through the seat mesh-hand-acts.
func dropWant(st seatStore, ask func(string, any) (json.RawMessage, error), node, module, why, by string) (any, error) {
switch {
case node == "" || module == "":
return nil, errors.New("name the node and the module whose want is dropped")
case why == "":
return nil, errors.New("a want dropped by hand says why")
case by == "" || by == stdio.Unproven:
return nil, errors.New("a want dropped by hand names who drops it, and the runtime proved no caller")
}
key, err := mwc.WantKey(node, module)
if err != nil {
return nil, err
}
raw, _, found, err := st.get(wantsState, key)
if err != nil {
return nil, err
}
if !found {
return nil, fmt.Errorf("the assigner holds no want under %s", key)
}
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: wantDropTool + " " + key, Why: why + " (" + by + ")", Cause: "want-drop"})
if err != nil {
return nil, fmt.Errorf("the drop of %s is not recorded, so the want stays: %w", key, err)
}
if err := st.del(wantsState, key); err != nil {
return nil, fmt.Errorf("the want %s is not dropped: %w", key, err)
}
return map[string]any{"key": key, "dropped": json.RawMessage(raw), "by": by, "hand-act": taken.Log}, nil
}
// The kinds the all form counts what it dropped by (design 47 H-A-123).
const (
dropHeld = "held"
dropCurrent = "current"
dropUndecodable = "undecodable"
)
// dropAllWants deletes every want key of the state wants, held or not, and every value of an earlier form the decoder refuses
// (the all form, design 47 H-A-121 (2), H-A-123): each act recorded through the seat mesh-hand-acts first, as the one-item form
// does; it answers what it dropped, counted per kind. A drop not recorded stops it, saying what went before.
func dropAllWants(st seatStore, ask func(string, any) (json.RawMessage, error), why, by string) (any, error) {
switch {
case why == "":
return nil, errors.New("a want dropped by hand says why")
case by == "" || by == stdio.Unproven:
return nil, errors.New("a want dropped by hand names who drops it, and the runtime proved no caller")
}
all, err := st.keys(wantsState)
if err != nil {
return nil, err
}
slices.Sort(all)
counted := map[string]int{dropHeld: 0, dropCurrent: 0, dropUndecodable: 0}
dropped := map[string][]string{}
answer := func() map[string]any {
return map[string]any{"dropped": dropped, "counted": counted, "by": by}
}
for _, key := range all {
if !strings.HasPrefix(key, "want.") {
continue
}
raw, _, found, err := st.get(wantsState, key)
if err != nil {
return answer(), fmt.Errorf("the want %s cannot be read, so the drop stops there: %w", key, err)
}
if !found {
continue
}
kind := wantKind(key, raw)
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: wantDropTool + " " + key, Why: why + " (" + by + ")", Cause: "want-drop"})
if err != nil {
return answer(), fmt.Errorf("the drop of %s is not recorded, so it and the wants after it stay: %w", key, err)
}
if err := st.del(wantsState, key); err != nil {
return answer(), fmt.Errorf("the want %s is not dropped: %w", key, err)
}
counted[kind]++
dropped[kind] = append(dropped[kind], key+" (hand act "+taken.Log+")")
}
return answer(), nil
}
// wantKind says how the all form counts a want: undecodable when its key or value is of no form the decoder takes, held when it
// holds, current otherwise (design 47 H-A-123).
func wantKind(key string, raw []byte) string {
if _, err := mwc.ParseWantNodeKey(key); err == nil {
if _, err := mwc.DecodeNodeWant(raw); err != nil {
return dropUndecodable
}
return dropCurrent
}
if _, _, err := mwc.ParseWantKey(key); err != nil {
return dropUndecodable
}
w, err := mwc.DecodeWant(raw)
switch {
case err != nil:
return dropUndecodable
case w.Hold:
return dropHeld
}
return dropCurrent
}
// wantDropTools is the tool over the runtime's states.
func wantDropTools(st seatStore, ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
return []stdio.Tool{{Name: wantDropTool, Description: "Drop one want by hand (design 47 H §765): the want of module on node is " +
"deleted from the state wants, as the clean state drops a held or failed want of the earlier model; the next pass writes the " +
"want of the new form. Recorded as a hand act first; refused with no want under the key. With all true and no node or module, " +
"every want key goes, held or not, and every value of an earlier form the decoder refuses, each recorded as a hand act; it " +
"answers what it dropped, counted per kind (held, current, undecodable).",
Input: schema(map[string]string{"node": "the node's name", "module": "the module's name", "why": "why the want is dropped",
"all": "true drops every want of the state wants, naming no node or module"}, []string{"why"}, "all"),
Run: func(a map[string]any) (any, error) {
if arg(a, "all") == "true" {
if arg(a, "node") != "" || arg(a, "module") != "" {
return nil, errors.New("the all form drops every want: name no node or module with it")
}
return dropAllWants(st, ask, arg(a, "why"), stdio.CallerOf(a))
}
return dropWant(st, ask, arg(a, "node"), arg(a, "module"), arg(a, "why"), stdio.CallerOf(a))
}}}
}
@@ -0,0 +1,99 @@
package main
import (
"encoding/json"
"errors"
"strings"
"testing"
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
)
// A12/AC1 (design 47 H §765, H-A-58): assigner_want_drop with node, module and why records the act in the hand-act log first
// and then deletes that want; with no want under the key, no why or no proven caller, and when the act is not recorded, nothing is
// dropped.
func TestAWantIsDroppedByHandAndRecorded(t *testing.T) {
key, _ := mwc.WantKey("ace", "web")
held, _ := mwc.EncodeWant(mwc.Want{Fp: fpTest, Put: true, Hold: true, Words: "put: x"})
for _, c := range []struct {
name, node, module, why, by string
refuse error
dropped bool
}{
{"dropped", "ace", "web", "the clean state", "person.jochen", nil, true},
{"no want there", "ace", "db", "the clean state", "person.jochen", nil, false},
{"no why", "ace", "web", "", "person.jochen", nil, false},
{"no caller", "ace", "web", "the clean state", "", nil, false},
{"not recorded", "ace", "web", "the clean state", "person.jochen", errors.New("no responders"), false},
} {
st := memStore{wantsState: &memKV{values: map[string][]byte{key: held}}}
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
}
out, err := dropWant(st, ask, c.node, c.module, c.why, c.by)
_, there := st[wantsState].values[key]
switch {
case c.dropped && (err != nil || there || len(asked) != 1 || !strings.Contains(asked[0], "seat:mesh-hand-acts.hand-act ") || !strings.Contains(asked[0], wantDropTool+" "+key)):
t.Errorf("%s: %v, %v; the want left %v, asked %v", c.name, out, err, there, asked)
case !c.dropped && (err == nil || !there):
t.Errorf("%s: %v, %v; the want left %v, want it refused and kept", c.name, out, err, there)
}
}
}
// H-A-121 (2), H-A-123: assigner_want_drop's all form drops every want key, held or not, and every value of an earlier form,
// each recorded as a hand act first, answering the count per kind; a held fingerprint's key stays; a drop not recorded stops it;
// the all form names no node or module.
func TestEveryWantIsDroppedByHandAndCounted(t *testing.T) {
heldKey, _ := mwc.WantKey("ace", "web")
curKey, _ := mwc.WantKey("ace", "db")
nodeKey, _ := mwc.WantNodeKey("ace")
oldKey, _ := mwc.WantKey("g14", "web")
fpKey, _ := mwc.HeldKey("web", fpTest)
held, _ := mwc.EncodeWant(mwc.Want{Fp: fpTest, Put: true, Hold: true, Words: "put: x"})
cur, _ := mwc.EncodeWant(mwc.Want{Fp: fpTest})
node, _ := mwc.EncodeNodeWant(mwc.NodeWant{Self: true})
values := func() map[string][]byte {
return map[string][]byte{heldKey: held, curKey: cur, nodeKey: node, oldKey: []byte(`{"fingerprint":"old"}`), fpKey: []byte(`{}`)}
}
for _, c := range []struct {
name string
refuse error
left int
}{
{"dropped", nil, 1},
{"not recorded", errors.New("no responders"), 5},
} {
st := memStore{wantsState: &memKV{values: values()}}
var asked []string
ask := func(verb string, body any) (json.RawMessage, error) {
raw, _ := json.Marshal(body)
asked = append(asked, string(raw))
return json.RawMessage(`{}`), c.refuse
}
out, err := dropAllWants(st, ask, "the clean state", "person.jochen")
if left := len(st[wantsState].values); left != c.left || (c.refuse == nil) != (err == nil) {
t.Errorf("%s: %v, %v; %d keys left, want %d", c.name, out, err, left, c.left)
}
if c.refuse != nil {
continue
}
if _, ok := st[wantsState].values[fpKey]; !ok {
t.Errorf("the held fingerprint's key %s is dropped: it is no want", fpKey)
}
counted := out.(map[string]any)["counted"].(map[string]int)
if counted[dropHeld] != 1 || counted[dropCurrent] != 2 || counted[dropUndecodable] != 1 || len(asked) != 4 {
t.Errorf("counted %v, asked %d hand acts; want held 1, current 2, undecodable 1 and 4 acts", counted, len(asked))
}
}
if _, err := dropAllWants(memStore{wantsState: &memKV{values: values()}}, nil, "", "person.jochen"); err == nil {
t.Error("the all form dropped with no why")
}
run := wantDropTools(memStore{wantsState: &memKV{values: values()}}, nil)[0].Run
if _, err := run(map[string]any{"all": "true", "node": "ace", "why": "x"}); err == nil || !strings.Contains(err.Error(), "name no node") {
t.Errorf("the all form with a node: %v, want it refused", err)
}
}
@@ -26,34 +26,36 @@ const whyTool = "assigner_why"
// The steps of the pass that decide a want.
const (
whyNoPipeline = "no-passed-pipeline" // the trunk's fingerprint passed no pipeline on the branch, and no want names it
whyDelivery = "waits-for-delivery" // a dependency's newest released version is not delivered yet
whyRules = "rules" // the six rules judged it
whyNoPipeline = "no-passed-pipeline" // no version of the module released on the branch passed its pipeline: the want written stays
whyPassed = "passed-pipeline" // the want names the newest version released on the branch whose pipeline passed (design 47 H §750)
)
// whyStep is the step that decided a want: a passed pipeline's version, or none yet.
func whyStep(passed bool) string {
if passed {
return whyPassed
}
return whyNoPipeline
}
// wantWhy is one key's value.
type wantWhy struct {
At time.Time `json:"at"`
Branch string `json:"branch,omitempty"`
// Fp is the fingerprint the trunk's entry names, the one the pass judged.
Fp string `json:"fp,omitempty"`
Step string `json:"step"`
// Fp, Version and Pipeline are the build the want names and the pipeline whose passed end released it (design 47 H §750).
Fp string `json:"fp,omitempty"`
Version string `json:"version,omitempty"`
Pipeline string `json:"pipeline,omitempty"`
Step string `json:"step"`
// Before is the want that stood before the pass, After the one the pass wrote (none: it kept Before).
Before *mwc.Want `json:"before,omitempty"`
After *mwc.Want `json:"after,omitempty"`
// Rule is the rule holding the node back from Fp, with its words.
Rule string `json:"rule,omitempty"`
// What the rules read of the module.
Built, BuildFailed, Held, Granted, Released, Kept bool `json:",omitempty"`
BuildError string `json:"build-error,omitempty"`
Acting []string `json:"acting,omitempty"`
Words string `json:"words,omitempty"`
}
func whyKey(node, module string) string { return whyPrefix + node + "." + module }
// sayWhy writes the why of module on each of nodes, once per change (the time aside): every put is a change its watchers hear.
func (p *passer) sayWhy(ctx context.Context, module string, nodes []string, w wantWhy, before map[string]mwc.Want, out *assign.Outcome, m *assign.Module) {
func (p *passer) sayWhy(ctx context.Context, module string, nodes []string, w wantWhy, before map[string]mwc.Want, out *assign.Outcome) {
kv := p.kvs[writtenBucket()]
if kv == nil {
return
@@ -71,17 +73,6 @@ func (p *passer) sayWhy(ctx context.Context, module string, nodes []string, w wa
if a, ok := out.Wants[node]; ok {
one.After = &a
}
if h, ok := out.Rules[node]; ok {
one.Rule = h.Reason()
}
}
if m != nil {
one.Built, one.BuildFailed, one.BuildError, one.Held, one.Granted, one.Released, one.Kept = m.Built, m.BuildFailed, m.BuildError, m.Held, m.Granted, m.Released, m.Kept
if m.Acting != nil {
for _, e := range m.Acting(node) {
one.Acting = append(one.Acting, e.Step+" "+e.Node+"/"+e.Part+"@"+shortHex(e.Fp)+" (seat "+e.Seat+")")
}
}
}
same := one
same.At = time.Time{}
@@ -104,7 +95,7 @@ func (p *passer) sayWhy(ctx context.Context, module string, nodes []string, w wa
// whyTools is the tool assigner_why: every want's why, or those of one module or one node.
func whyTools(st store) []stdio.Tool {
return []stdio.Tool{{Name: whyTool, Description: "why a want is what it is: per node and module, the step of the assigner's last pass that decided the want (no passed pipeline, waits for a dependency's delivery, or the six rules with the rule holding it back), the fingerprint the trunk names, the want before and the one written, and what the rules read (built, held, granted, acting waits). A time that stands still says the pass no longer judges that module. Arguments: module and node narrow it.",
return []stdio.Tool{{Name: whyTool, Description: "why a want is what it is: per node and module, the step of the assigner's last pass that decided the want (no passed pipeline yet, or a passed pipeline's version), the build, version and pipeline it names, the want before and the one written. A time that stands still says the pass no longer judges that module. Arguments: module and node narrow it.",
Input: schema(map[string]string{"module": "a module's name", "node": "a node's name"}, nil),
Run: func(args map[string]any) (any, error) {
ks, err := st.keys(writtenState)
@@ -12,7 +12,6 @@ import (
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
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"
@@ -43,12 +42,8 @@ type world struct {
ends builtEnds
// released are the catalog's version-released heard, by module and source revision (buildended.go).
released releasedVersions
// delivered are the assigner's own version-delivered heard and said (delivered.go).
delivered deliveredVersions
// edges are, by watched branch and module, the edges into the module's artifacts its catalog entry names (§374's kinds).
edges map[string]map[string][]meshcatalog.Edge
// taken is the newest source revision of each watched branch the indexer's take-in.taken named, as heard (orderwaits.go, §298, A-260).
taken takenSources
// assignments is the seat's state assignments assembled node by node from its keys in either form (mesh-sdk
// mmac.Keys; research 072 row 37): the one reader of its keys in the assigner.
assignmentKeys *mmac.Keys
@@ -139,23 +134,6 @@ func (w *world) put(bucket, key string, value []byte) {
}
}
// lastHealthy is the newest fingerprint other than fp the node ran the module healthy at, or empty.
func (w *world) lastHealthy(node, module, fp string) string {
key, err := nodeengineclient.HaveKey(node, module)
if err != nil {
return ""
}
w.mu.Lock()
defer w.mu.Unlock()
list := w.healthy[key]
for i := len(list) - 1; i >= 0; i-- {
if list[i] != fp {
return list[i]
}
}
return ""
}
// read is a copy of what a bucket holds now.
func (w *world) read(bucket string) map[string][]byte {
w.mu.Lock()
@@ -407,30 +385,14 @@ func (w *world) wantsOf() map[string]map[string]mwc.Want {
// nodes is what the six rules read of the nodes: presence, haves, and every provision's providers with their nodes.
func (w *world) nodes(manifests map[string]catalogue.Manifest, assigned map[string][]string) assign.Nodes {
n := assign.Nodes{Online: map[string]bool{}, Running: w.runningNow(), Haves: map[string]map[string]nodeengine.HaveByNodeModuleValue{}, Providers: map[string]map[string][]string{},
Reads: map[string][]string{}, Capable: map[string][]string{}}
Reads: map[string][]string{}}
n.Online = w.online()
// The build a running statement names serves an acting edge's seat when its manifest claims it (design 47 G A-426).
n.Serves = func(r nodeengine.Running, seat string) (bool, bool) {
if r.Manifest == "" {
return false, false
}
got := w.manifest(r.Manifest)
if got.err != "" {
return false, false
}
return got.manifest.ClaimsSeat(seat), true
}
for key, value := range w.read(buckets.Have) {
node, module, isNode, err := nodeengineclient.ParseHaveKey(key)
if err != nil {
continue
}
if isNode {
// What the node's engine reads (ADR 0614 §4); a record that states none is read as the baseline.
if h, err := nodeengineclient.DecodeHaveNode(value); err == nil && h.Record != nil {
n.Reads[node] = h.Record.ManifestReads
n.Capable[node] = h.Record.Capabilities // where a node-engine of G states want-parts (§525)
}
if isNode { // what the node's engine reads is the state engine-reads' alone (design 47 H-A-104)
continue
}
if h, err := nodeengineclient.DecodeHave(value); err == nil {
@@ -476,37 +438,6 @@ func (w *world) has(bucket, key string) bool {
return ok
}
// built says whether the builder's build of a module at a fingerprint is done, from its `build.ended` heard (design 47 G A-181).
func (w *world) built(module, fp string) bool {
e, ok := w.ends.endOf(module, fp)
return ok && e.Outcome == builds.BuildDone
}
// buildStanding says whether the builder's `build.ended` of module at fp said the build failed, and its error whole (design 47 G
// §575, A-162): the words of a hold under rule 1.
func (w *world) buildStanding(module, fp string) (failed bool, words string) {
if e, ok := w.ends.endOf(module, fp); ok && e.Outcome == builds.BuildFailed {
return true, e.Error
}
return false, ""
}
// buildNeeds are the reference forms the builder's done build of module at fp is written in (the build's end says them, ADR
// 0618 §1, A-181): nil when it is not done or names none.
func (w *world) buildNeeds(module, fp string) []string {
if e, ok := w.ends.endOf(module, fp); ok && e.Outcome == builds.BuildDone {
return e.Needs
}
return nil
}
// recordReads is what node's record `<node>.node` states its engine reads (ADR 0614 §4), and whether the assigner holds
// a record of it: the fallback where the engine does not answer the verb manifest-reads (enginereads.FromRecord).
func (w *world) recordReads(node string) ([]string, bool) {
r, ok := w.records()[node]
return r.ManifestReads, ok
}
// knownNodes is every node the assigner hears of: placed, with a record, or named by machine-away or machine-back.
func (w *world) knownNodes() []string {
set := map[string]bool{}
@@ -622,3 +553,18 @@ func (w *world) placedBranches() map[string]map[string]string {
}
return out
}
// assignedOn is the modules the assignments place on node.
func (w *world) assignedOn(node string) []string {
var out []string
for _, m := range w.assignments()[node].Modules {
out = append(out, m.Module)
}
return out
}
// assignmentOf is node's assignments, or false where none is held.
func (w *world) assignmentOf(node string) (mma.Assignments, bool) {
a, ok := w.assignments()[node]
return a, ok
}
-3
View File
@@ -89,16 +89,13 @@ replace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view/viewstate =>
require git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient v0.0.0-00010101000000-000000000000
require git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient v0.0.0-00010101000000-000000000000
replace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient => ../mesh-delivery-contracts/go/clients/meshdeliverycheckerclient
require git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/theprivatenetwork v0.0.0-00010101000000-000000000000 // indirect
)
@@ -1,140 +0,0 @@
// Package acting is the assigner's wait for an acting part's new version (design 47 G §266, §268, §276): an entry of the assignment
// graph whose edge of kind acting names a step the assigner holds (composing, placing) waits until the acting part's version runs
// on the node of the edge, with the bound of the rule that gave the edge, or the step's default. The package holds the rules and
// the kept record; the assigner's process reads what runs, says the events and keeps the records in its state `waits`.
package acting
import (
"encoding/json"
"fmt"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// HowNow is the `how` of assigner_release for a wait for an acting part: the entry is wanted now, with the version running.
const HowNow = "now"
// The ways a wait ends, as `wait-ended` says them.
const (
HowRan = "ran"
HowReleased = "released"
HowReplaced = "replaced"
)
// Prefix opens the key of an acting wait in the state, apart from the outside waits' `<node>.<module>.<fingerprint hex>`.
const Prefix = "acting."
// OrderPrefix opens the key of an order wait (design 47 G §298, A-259): a want held for the order of a delivery that crosses a form change,
// kept beside the acting waits in the state `waits`, as `order.<node>.<module>.<part>`.
const OrderPrefix = "order."
// The three order edges of §298, as a kept wait's Order names them.
const (
// OrderBackup: the new versions of the node-backup holder and of the holder of the bus module's seat run before a module whose kept
// data's form changes is moved.
OrderBackup = "backup-and-broker-first"
// OrderEngineLast: at a revert a node's node-engine goes back last on that node.
OrderEngineLast = "node-engine-last"
// OrderTakenIn: the reverted assigner and gate are wanted only once the reverted indexer took in the trunk's head.
OrderTakenIn = "taken-in-first"
)
// Held says whether the assigner holds the entries of step: composing and placing (§276's table).
func Held(step string) bool { return step == seatdef.StepCompose || step == seatdef.StepPlace }
// Wait is one wait as kept: Module's entry on Node waits for Part's version Fp to run on PartNode, in Step.
type Wait struct {
V int `json:"v"`
Step string `json:"step"`
Node string `json:"node"`
Module string `json:"module"`
Part string `json:"part"`
PartNode string `json:"part-node"`
Fp string `json:"fp"`
Entry string `json:"entry"`
Since time.Time `json:"since"`
ClockFrom time.Time `json:"clock-from"`
Bound string `json:"bound"`
// Released is a release by hand: the entry moves on with the part's old version; EndSaid says wait-ended was said for it.
// Order is which of §298's edges the wait stands on; empty for an acting wait.
Order string `json:"order,omitempty"`
Released bool `json:"released,omitempty"`
EndSaid bool `json:"end-said,omitempty"`
By string `json:"by,omitempty"`
Why string `json:"why,omitempty"`
}
// Key is the key of a wait in the state.
func Key(node, module, part string) string { return Prefix + node + "." + module + "." + part }
// OrderKey is the key of an order wait in the state.
func OrderKey(node, module, part string) string {
return OrderPrefix + node + "." + module + "." + part
}
// IsOrder says a kept value is an order wait's record.
func IsOrder(key string) bool { return strings.HasPrefix(key, OrderPrefix) }
// Is says a kept value is an acting wait's record.
func Is(key string) bool { return strings.HasPrefix(key, Prefix) }
// Encode is w as JSON.
func Encode(w Wait) ([]byte, error) { w.V = 1; return json.Marshal(w) }
// Decode reads a kept wait.
func Decode(raw []byte) (Wait, error) {
var w Wait
if err := json.Unmarshal(raw, &w); err != nil {
return w, err
}
if w.V != 1 || w.Step == "" || w.Node == "" || w.Module == "" || w.Part == "" {
return w, fmt.Errorf("acting: %q is not a kept acting wait", raw)
}
return w, nil
}
// BoundOf is the bound of the edge's wait: its rule's, else its step's default (seatdef.ActingRule.Wait).
func BoundOf(e meshwants.Edge) time.Duration {
return seatdef.ActingRule{Step: e.Step, Bound: e.Bound}.Wait()
}
// Pending are the acting edges of the assigner's steps whose part's version does not run yet: runs says the edge's part runs
// its version on the edge's node.
func Pending(edges []meshwants.Edge, runs func(e meshwants.Edge) bool) []meshwants.Edge {
var out []meshwants.Edge
for _, e := range edges {
if e.Kind == "acting" && Held(e.Step) && !runs(e) {
out = append(out, e)
}
}
return out
}
// Body is the wait as the seat mesh-wants says it.
func Body(w Wait, owner string) meshwants.Wait {
since, from := w.Since.UTC(), w.ClockFrom.UTC()
return meshwants.Wait{Step: w.Step, Owner: owner, Node: w.Node, Module: w.Module, Part: w.Part, Fp: w.Fp, Since: since, ClockFrom: &from, Bound: w.Bound,
Words: words(w)}
}
func words(w Wait) string {
switch w.Order {
case OrderBackup:
return fmt.Sprintf("%s on %s moves its kept data across a form change: it waits in %s for %s at %s to run on %s, which the restore point needs", w.Module, w.Node, w.Step, w.Part, short(w.Fp), w.PartNode)
case OrderEngineLast:
return fmt.Sprintf("%s on %s goes back last on its node: it waits in %s for %s at %s to run on %s, restored", w.Module, w.Node, w.Step, w.Part, short(w.Fp), w.PartNode)
case OrderTakenIn:
return fmt.Sprintf("%s on %s goes back only once the indexer took in the trunk's head: it waits in %s for source revision %s to be taken in", w.Module, w.Node, w.Step, w.Fp)
}
return fmt.Sprintf("%s on %s waits in %s for %s at %s to run on %s", w.Module, w.Node, w.Step, w.Part, short(w.Fp), w.PartNode)
}
func short(fp string) string {
if len(fp) > 19 {
return fp[:19]
}
return fp
}
@@ -3,7 +3,6 @@ package assign
import (
"fmt"
"mesh-delivery-assigner/internal/assignment"
"regexp"
"strings"
"time"
@@ -16,56 +15,12 @@ import (
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
)
// HoldAsk is the ask about a module's fingerprint the assigner holds, at its key (asks.HoldAskKey): keep it held or
// release it. Releasing writes the held fingerprint's want again by the rules (ADR 0539 §19). node and words are the held
// record's: the machine whose health check failed and the hold's words (issue 1906). asking numbers the writing: 0 the first, a
// larger number an ask written again after a hold lifted by itself, so the router takes it as new.
func HoldAsk(key, module, fp, node, words string, asking int, now time.Time) asks.Ask {
return assignerAsk(asking, oc.Ask{
ID: meshdeliveryclient.AskingID(key, asking),
Headline: fmt.Sprintf("%s is held at %s", module, short(fp)),
Explanation: fmt.Sprintf("The health check of %s failed on %s at %s (%s), so the assigner holds that version and wants "+
"no node to move to it. It lifts the hold by itself once every node that runs %s runs it healthy; releasing it "+
"lets the wants move to it now.", module, node, short(fp), words, module),
Options: []oc.Option{
{ID: "keep", Label: "Keep it held", Does: "the version stays held", Level: occ.Acknowledge},
{ID: "release", Label: "Release it", Does: "the version is released and the wants move to it by the rules again", Level: occ.Acknowledge},
},
Who: occ.Operator,
Expires: occ.FormatTime(now.Add(AskLasts)),
OnExpiry: "the version stays held",
About: key,
})
}
// The options of the restore ask (ADR 0537 §3, ADR 0539 §19), and what each does on the node.
const (
OptionRestore = "restore"
OptionLeaveStopped = "leave-stopped"
)
// RestoreAsk is the ask about a module holding data whose fingerprint failed its health check on a node (ADR 0429 §6): it is
// not set back by itself, since a set-back would lose the writes made since. words is the check's words. asking is the writing's
// number (AskingSeconds): an ask taken away as stale and written again is another asking under an id of its own, since the
// router drops a second ask under an id it keeps and the teller took the first back (issue 1966). Restore sets the
// node back to the last healthy fingerprint and loses the newer writes; leaving it stopped keeps the data as it is.
func RestoreAsk(key, node, module, fp, words string, asking int, now time.Time) asks.Ask {
return assignerAsk(asking, oc.Ask{
ID: meshdeliveryclient.AskingID(key, asking),
Headline: fmt.Sprintf("%s failed its health check on %s", module, node),
Explanation: fmt.Sprintf("%s holds data, and its health check failed on %s at %s: %s. Setting it back to the version that ran healthy "+
"would lose the writes made since; leaving it stopped keeps the data as it is.", module, node, short(fp), words),
Options: []oc.Option{
{ID: OptionRestore, Label: "Restore it", Does: "the node is set back to the last healthy version and the newer writes are lost", Level: occ.Acknowledge},
{ID: OptionLeaveStopped, Label: "Leave it stopped", Does: "the module stays as it is on the node and the data is kept", Level: occ.Acknowledge},
},
Who: occ.Operator,
Expires: occ.FormatTime(now.Add(AskLasts)),
OnExpiry: "the module stays as it is on the node",
About: key,
})
}
// The options of the outside ask (design 47 G §706).
const (
OptionGoOn = "go-on"
@@ -106,92 +61,6 @@ func WaitsOutsideFinding(node, module, causeKey, on string, at time.Time) Observ
Needs: "Nothing for you to do.", Source: "assigner.delivery-waits-outside"}
}
// HeldCondition is the condition the assigner raises when it holds a fingerprint of a module (ADR 0429 §6, ADR 0539 §19), or
// clears (raised false) when the hold is released. It names the module, the node whose health check failed and the check's
// words, under the assigner's own name (ADR 0437 clause 9), keyed by the held fingerprint. needsYou is true for a module holding
// data, whose restore ask waits for the operator.
func HeldCondition(module, fp, node, words string, raised, needsYou bool) oc.Condition {
key := assignment.Module() + ".held." + module + "." + strings.TrimPrefix(fp, meshcatalogclient.SourcePrefix2)
subject := oc.ConditionSubject{Scope: "module", ID: module, Machine: node}
if !raised {
return oc.Condition{Key: key, Subject: subject, State: occ.StateCleared}
}
c := oc.Condition{Key: key, Severity: occ.SeverityWarning, Subject: subject, State: occ.StateRaised,
Summary: fmt.Sprintf("%s is held at %s", module, short(fp)),
Headline: fmt.Sprintf("%s is held at %s", module, short(fp))}
what := fmt.Sprintf("The health check of %s failed on %s at %s: %s. The assigner holds that version and wants no node to move to it.", module, node, short(fp), words)
if needsYou {
c.Needs = "answer whether to restore " + module + " on " + node
c.Explanation = occ.NeedsYou + c.Needs + ". " + what
} else {
c.Explanation = occ.NothingToDo + " " + what + " Nodes that wanted it are set back to the version that ran healthy."
}
return c
}
// NodeFailedCondition is the condition the assigner raises for a module whose newest fingerprint fp failed its health check on
// node while other nodes run it healthy (ADR 0557 §1, issue 1496): the failure is the node's, so nothing is held or set back and
// the node keeps its want. It names the node, the module, fp and the have's words, keyed by node and module, and is cleared
// (raised false) once the node no longer fails alone.
func NodeFailedCondition(node, module, fp string, f NodeFailure, raised bool) oc.Condition {
key := assignment.Module() + ".failed-alone." + node + "." + module
subject := oc.ConditionSubject{Scope: "module", ID: module, Machine: node}
if !raised {
return oc.Condition{Key: key, Subject: subject, State: occ.StateCleared,
Resolved: fmt.Sprintf("%s on %s no longer fails its health check alone.", module, node)}
}
headline := fmt.Sprintf("%s fails on %s alone", module, node)
if n := len([]rune(headline)); n > occ.HeadlineLength {
headline = string([]rune(headline)[:occ.HeadlineLength])
}
return oc.Condition{Key: key, Severity: occ.SeverityWarning, Subject: subject, State: occ.StateRaised,
Summary: headline, Headline: headline,
Explanation: fmt.Sprintf("%s The health check of %s at %s failed on %s (%s), while it runs healthy on %s. The failure is %s's, "+
"so the assigner holds nothing and sets no node back, and %s keeps its want. This clears once %s runs it healthy or "+
"another version is the newest.", occ.NothingToDo, module, short(fp), node, f.Words, strings.Join(f.Others, ", "), node,
node, node)}
}
// NeitherCondition is the condition of a module assigned to node that holds no want for it (issue 1945): the node's own composition
// gives up every module with a fingerprint of the new form, so nothing applies it there and its files are gone. It is raised (urgent)
// naming the module, the node and the rule holding its first want back with the rule's words, under the assigner's own name keyed by
// node and module, and cleared (raised false) when the node has a want for it again.
func NeitherCondition(node, module string, h Holding, raised bool) oc.Condition {
key := assignment.Module() + ".neither." + node + "." + module
subject := oc.ConditionSubject{Scope: "module", ID: module, Machine: node}
if !raised {
return oc.Condition{Key: key, Subject: subject, State: occ.StateCleared,
Resolved: fmt.Sprintf("%s on %s has a want again, so its own composition is applied there.", module, node)}
}
headline := fmt.Sprintf("%s on %s is on no list", module, node)
if n := len([]rune(headline)); n > occ.HeadlineLength {
headline = string([]rune(headline)[:occ.HeadlineLength])
}
return oc.Condition{Key: key, Severity: occ.SeverityUrgent, Subject: subject, State: occ.StateRaised,
Summary: headline, Headline: headline,
Explanation: fmt.Sprintf("%s %s is assigned to %s, but the node holds no want for it and the node's own composition does not "+
"hold it either, so nothing applies it there. The assigner's rule %d holds its first want back: %s. The assigner writes the want once the "+
"rule holds, and clears this.", occ.NothingToDo, module, node, h.Rule, h.Words)}
}
// NeitherLeftCondition clears the neither condition of module on node when it is no longer on neither list: why is "" when the
// node has a live want for it again, else why it has none (it is held, its move waits for an ask, the node no longer runs it), so
// the clear never says a want the node does not hold (issue 1945: "nats on novox has a want again" while it had none).
func NeitherLeftCondition(node, module, why string) oc.Condition {
c := NeitherCondition(node, module, Holding{}, false)
if why != "" {
c.Resolved = fmt.Sprintf("%s on %s is no longer on neither list and has no want: %s.", module, node, why)
}
return c
}
// LiftedCondition clears the condition of a held fingerprint the assigner lifted by itself, saying why (issue 1906).
func LiftedCondition(module, fp string) oc.Condition {
c := HeldCondition(module, fp, "", "", false, false)
c.Resolved = LiftedWords(module, fp) + "."
return c
}
// The options of the record ask (ADR 0539 §14) and of the backup ask (§16).
const (
OptionYes = "yes"
@@ -288,27 +157,6 @@ func NextBackupAsking(after int) int {
return max(after+1, 2)
}
var backupDigest = regexp.MustCompile(`\(composition (sha256:[0-9a-f]{12})\)`)
// BackupAskDigest is the digest of the composition a backup ask was made about, from its explanation, cut to its first 12 digits as
// the ask says it (ShortDigest); empty for an ask that names
// none. An answer is taken for the composition of the ask it answers, and a new revision at the same fingerprint is asked again
// under a new number (ADR 0539 §16).
func BackupAskDigest(a asks.Ask) string {
ask, err := AskOf(a)
if err != nil {
return ""
}
if m := backupDigest.FindStringSubmatch(ask.Explanation); m != nil {
return m[1]
}
return ""
}
// ShortDigest is a composition's digest as a backup ask names it, its first 12 digits (said): the ask stays bound to its
// composition, and a new composition is asked again.
func ShortDigest(digest string) string { return said(digest) }
// BackupAnswerWords are the words of a want carrying the answer to the asking-th ask: each asking's answer is another want
// value, so a backup that fails again after "back up again" and is answered "again" again changes the key and the node retries.
func BackupAnswerWords(option string, asking int) string {
@@ -316,14 +164,14 @@ func BackupAnswerWords(option string, asking int) string {
}
// BackupAsk is the ask about a backup of a module on node that failed before an apply (ADR 0539 §16): back up again, or go on
// without a backup. digest is the composition about to be applied and asking the number of the asking, 0 the first; words are the
// without a backup, at the build fp the want names. asking is the number of the asking, 0 the first; words are the
// backup's own words, from the node's have.
func BackupAsk(key, node, module, fp, digest, words string, asking int, now time.Time) asks.Ask {
func BackupAsk(key, node, module, fp, words string, asking int, now time.Time) asks.Ask {
return assignerAsk(asking, oc.Ask{
ID: meshdeliveryclient.AskingID(key, asking),
Headline: fmt.Sprintf("The backup of %s failed on %s", module, node),
Explanation: fmt.Sprintf("The backup before applying %s at %s on %s failed: %s. %s keeps running what it has until you answer. (composition %s)",
module, short(fp), node, words, module, digest),
Explanation: fmt.Sprintf("The backup before applying %s at %s on %s failed: %s. %s keeps running what it has until you answer.",
module, short(fp), node, words, module),
Options: []oc.Option{
{ID: OptionBackupAgain, Label: "Back up again", Does: "the node tries the backup again before it applies", Level: occ.Acknowledge},
{ID: OptionBackupSkip, Label: "Go on without a backup", Does: "the node applies the new version without a backup", Level: occ.Acknowledge},
@@ -23,11 +23,10 @@ import (
"git.novox.be/novox/mesh-sdk/go/views"
)
// 1297/B9 (the assigner's half): the ask about a held fingerprint is a valid ask of the router and of mesh-sdk's layout at
// its key, of a kind the view may answer.
func TestTheHoldAskIsValid(t *testing.T) {
t.Run("hold", theHoldAskIsValid)
t.Run("restore", theRestoreAskIsValid)
// 1297/B9 (the assigner's half): the backup ask is a valid ask of the router and of mesh-sdk's layout at its key, of a kind the
// view may answer; the hold and restore asks went with the hold of a fingerprint (design 47 H §750, H-A-55).
func TestTheAssignersAsks(t *testing.T) {
t.Run("backup", theBackupAskIsValid)
t.Run("ended at the channel", anAskEndedAtTheChannelIsWrittenAgain)
t.Run("ended at the channel, read at bind", anAskEndedAtTheChannelIsReadAtBind)
}
@@ -40,8 +39,6 @@ func anAskEndedAtTheChannelIsWrittenAgain(t *testing.T) {
asked := time.Date(2026, 11, 9, 22, 0, 0, 0, time.UTC)
now := asked.Add(8 * 24 * time.Hour)
digest := "sha256:" + strings.Repeat("e", 64)
holdKey, _ := asks.HoldAskKey("nats", fNew)
restoreKey, _ := asks.RestoreAskKey("novox", "nats", fNew)
backupKey, _ := asks.BackupAskKey("novox", "nats", fNew)
revertKey, _ := asks.RevertAskKey("novox", "nats", fNew)
recordKey, _ := asks.RecordAskKey("novox", "nats", digest)
@@ -63,9 +60,7 @@ func anAskEndedAtTheChannelIsWrittenAgain(t *testing.T) {
put *puts.Put
why string // "" when it is written again
}{
{name: "hold", key: holdKey, a: ptr(HoldAsk(holdKey, "nats", fNew, "novox", "w", AskingSeconds(asked), asked)), outcome: occ.OutcomeExpired},
{name: "restore", key: restoreKey, a: ptr(RestoreAsk(restoreKey, "novox", "nats", fNew, "w", AskingSeconds(asked), asked)), outcome: occ.OutcomeCancelled},
{name: "backup", key: backupKey, a: ptr(BackupAsk(backupKey, "novox", "nats", fNew, digest, "w", 0, asked)), outcome: occ.OutcomeCancelled},
{name: "backup", key: backupKey, a: ptr(BackupAsk(backupKey, "novox", "nats", fNew, "w", 0, asked)), outcome: occ.OutcomeCancelled},
{name: "revert", key: revertKey, a: ptr(assignerAsk(AskingSeconds(asked), oc.Ask{ID: meshdeliveryclient.AskingID(revertKey, AskingSeconds(asked)),
Headline: "h", Explanation: "e", Who: occ.Operator, Expires: occ.FormatTime(asked.Add(AskLasts)), OnExpiry: "o",
Options: []oc.Option{{ID: "hold", Label: "Hold", Does: "d", Level: occ.Acknowledge}}})), outcome: occ.OutcomeExpired},
@@ -73,11 +68,11 @@ func anAskEndedAtTheChannelIsWrittenAgain(t *testing.T) {
{name: "record of another put", key: recordKey, a: &record, outcome: occ.OutcomeExpired, put: &other},
{name: "record a put asked", key: recordKey, a: &byPut, outcome: occ.OutcomeExpired, put: &put, why: "put"},
{name: "assignments", key: assignmentsKey, a: &assignments, outcome: occ.OutcomeExpired, why: "ADR 0567"},
{name: "another asking stands", key: holdKey, a: ptr(HoldAsk(holdKey, "nats", fNew, "novox", "w", AskingSeconds(now), now)),
ended: meshdeliveryclient.AskingID(holdKey, AskingSeconds(asked)), outcome: occ.OutcomeExpired, why: "holds the asking"},
{name: "taken away", key: holdKey, ended: "hold-x", outcome: occ.OutcomeExpired, why: "taken away"},
{name: "refused", key: holdKey, a: ptr(HoldAsk(holdKey, "nats", fNew, "novox", "w", 0, asked)), outcome: occ.OutcomeRefused, why: "refused"},
{name: "replaced", key: holdKey, a: ptr(HoldAsk(holdKey, "nats", fNew, "novox", "w", 0, asked)), outcome: occ.OutcomeReplaced, why: "replaced"},
{name: "another asking stands", key: backupKey, a: ptr(BackupAsk(backupKey, "novox", "nats", fNew, "w", AskingSeconds(now), now)),
ended: meshdeliveryclient.AskingID(backupKey, AskingSeconds(asked)), outcome: occ.OutcomeExpired, why: "holds the asking"},
{name: "taken away", key: backupKey, ended: "backup-x", outcome: occ.OutcomeExpired, why: "taken away"},
{name: "refused", key: backupKey, a: ptr(BackupAsk(backupKey, "novox", "nats", fNew, "w", 0, asked)), outcome: occ.OutcomeRefused, why: "refused"},
{name: "replaced", key: backupKey, a: ptr(BackupAsk(backupKey, "novox", "nats", fNew, "w", 0, asked)), outcome: occ.OutcomeReplaced, why: "replaced"},
} {
t.Run(c.name, func(t *testing.T) {
var current []byte
@@ -134,12 +129,12 @@ func anAskEndedAtTheChannelIsWrittenAgain(t *testing.T) {
// answered or another asker's ask, and one the key no longer holds, are not.
func anAskEndedAtTheChannelIsReadAtBind(t *testing.T) {
asked := time.Date(2026, 11, 9, 22, 0, 0, 0, time.UTC)
holdKey, _ := asks.HoldAskKey("nats", fNew)
restoreKey, _ := asks.RestoreAskKey("novox", "nats", fNew)
backupKey, _ := asks.BackupAskKey("novox", "nats", fNew)
hold := HoldAsk(holdKey, "nats", fNew, "novox", "w", AskingSeconds(asked), asked)
restore := RestoreAsk(restoreKey, "novox", "nats", fNew, "w", AskingSeconds(asked.Add(time.Hour)), asked.Add(time.Hour))
backup := BackupAsk(backupKey, "novox", "nats", fNew, "sha256:"+strings.Repeat("e", 64), "w", 0, asked.Add(-time.Hour)) // no asking
holdKey, _ := asks.BackupAskKey("g14", "nats", fNew)
restoreKey, _ := asks.BackupAskKey("ace", "nats", fNew)
hold := BackupAsk(holdKey, "g14", "nats", fNew, "w", AskingSeconds(asked), asked)
restore := BackupAsk(restoreKey, "ace", "nats", fNew, "w", AskingSeconds(asked.Add(time.Hour)), asked.Add(time.Hour))
backup := BackupAsk(backupKey, "novox", "nats", fNew, "w", 0, asked.Add(-time.Hour)) // no asking
held := map[string][]byte{}
for key, a := range map[string]asks.Ask{holdKey: hold, restoreKey: restore, backupKey: backup} {
v, err := EncodeAsk(key, a)
@@ -174,27 +169,27 @@ func anAskEndedAtTheChannelIsReadAtBind(t *testing.T) {
func ptr(a asks.Ask) *asks.Ask { return &a }
func theHoldAskIsValid(t *testing.T) {
key, err := asks.HoldAskKey("mail", fNew)
func theBackupAskIsValid(t *testing.T) {
key, err := asks.BackupAskKey("ace", "mail", fNew)
if err != nil {
t.Fatal(err)
}
now := time.Now()
a := HoldAsk(key, "mail", fNew, "ace", "health failed, phase running: connection refused", 0, now)
a := BackupAsk(key, "ace", "mail", fNew, "health failed, phase running: connection refused", 0, now)
if err := occ.Check(mustAsk(t, a), now); err != nil {
t.Errorf("the router refuses the ask: %v", err)
}
if _, err := EncodeAsk(key, a); err != nil {
t.Errorf("the ask cannot be written: %v", err)
}
// 1906/H3: the ask names the machine whose check failed and the hold's words.
// The ask names the machine whose backup failed and the backup's words.
if !strings.Contains(mustAsk(t, a).Explanation, "on ace") || !strings.Contains(mustAsk(t, a).Explanation, "connection refused") {
t.Errorf("the ask does not name the node and the hold's words: %q", mustAsk(t, a).Explanation)
}
// 1906/H2: an ask written again after a lift is another asking, under an id of its own.
again := HoldAsk(key, "mail", fNew, "ace", "x", 7, now)
// An ask written again is another asking, under an id of its own.
again := BackupAsk(key, "ace", "mail", fNew, "x", 7, now)
if again.Asking != 7 || mustAsk(t, again).ID != meshdeliveryclient.AskingID(key, 7) || mustAsk(t, again).ID == mustAsk(t, a).ID {
t.Errorf("the asking after a lift = %d %s", again.Asking, mustAsk(t, again).ID)
t.Errorf("the asking again = %d %s", again.Asking, mustAsk(t, again).ID)
}
if _, err := EncodeAsk(key, again); err != nil {
t.Errorf("the ask asked again cannot be written: %v", err)
@@ -204,7 +199,7 @@ func theHoldAskIsValid(t *testing.T) {
}
// The join (A1d ruling 1): mesh-sdk no longer refuses another id, no option or no ask in an assigner's ask; EncodeAsk does.
t.Run("EncodeAsk refuses what mesh-sdk no longer does", func(t *testing.T) {
good := HoldAsk(key, "mail", fNew, "ace", "x", 0, time.Unix(100, 0))
good := BackupAsk(key, "ace", "mail", fNew, "x", 0, time.Unix(100, 0))
other := good
other.Asking = 3 // its id is the asking 0's
empty := good
@@ -219,68 +214,11 @@ func theHoldAskIsValid(t *testing.T) {
})
}
// 1906/D3 (ADR 0539 §19): the ask about a data module held on a node is a valid ask of the router and of mesh-sdk's layout at
// its restore key, of a kind the view may answer; it offers restoring (losing the newer writes) and leaving it stopped.
func theRestoreAskIsValid(t *testing.T) {
key, err := asks.RestoreAskKey("ace", "mail", fNew)
if err != nil {
t.Fatal(err)
}
now := time.Now()
a := RestoreAsk(key, "ace", "mail", fNew, "connection refused", 2, now)
if err := occ.Check(mustAsk(t, a), now); err != nil {
t.Errorf("the router refuses the ask: %v", err)
}
if _, err := EncodeAsk(key, a); err != nil {
t.Errorf("the ask cannot be written: %v", err)
}
if _, err := viewstate.ViewAnswerKey(key); err != nil {
t.Errorf("the view may not answer it: %v", err)
}
var ids []string
for _, o := range mustAsk(t, a).Options {
ids = append(ids, o.ID)
}
if len(ids) != 2 || ids[0] != OptionRestore || ids[1] != OptionLeaveStopped {
t.Errorf("options = %v", ids)
}
if !strings.Contains(mustAsk(t, a).Explanation, "connection refused") || !strings.Contains(mustAsk(t, a).Explanation, "ace") {
t.Errorf("the ask does not name the node and the check's words: %q", mustAsk(t, a).Explanation)
}
}
// 1906/D3: the condition for a held fingerprint names the module, the node and the check's words, under the assigner's own
// name (ADR 0437 clause 9), and is cleared under the same key.
// 1952/WM6: the assigner's conditions are findings.
func TestTheAssignersConditions(t *testing.T) {
t.Run("the held condition names module, node and words", heldConditionNamesModuleNodeAndWords)
t.Run("a lifted hold clears its condition saying why", liftedHoldClearsItsConditionSayingWhy)
t.Run("1952/WM6: each said condition is a finding, its clear deletes it, said straight only with no findings bucket", saidConditionsAreFindings)
}
func heldConditionNamesModuleNodeAndWords(t *testing.T) {
c := HeldCondition("mail", fNew, "ace", "connection refused", true, true)
if _, err := occ.EncodeCondition(c); err != nil {
t.Fatalf("the condition is refused: %v", err)
}
if c.State != occ.StateRaised || c.Subject.ID != "mail" || c.Subject.Machine != "ace" || !strings.Contains(c.Explanation, "connection refused") || !strings.Contains(c.Key, "mail") {
t.Errorf("condition = %+v", c)
}
if got := HeldCondition("mail", fNew, "", "", false, false); got.State != occ.StateCleared || got.Key != c.Key {
t.Errorf("cleared = %+v", got)
}
}
// 1906/H2: a hold lifted by itself clears the held condition under its key, saying why.
func liftedHoldClearsItsConditionSayingWhy(t *testing.T) {
c := LiftedCondition("mail", fNew)
if _, err := occ.EncodeCondition(c); err != nil {
t.Fatalf("the condition is refused: %v", err)
}
if c.State != occ.StateCleared || c.Key != HeldCondition("mail", fNew, "ace", "x", true, false).Key || !strings.Contains(c.Resolved, "lifted its hold by itself") {
t.Errorf("condition = %+v", c)
}
}
// 1952/WM6 (ADR 0564 §2, issue 1952 note 16): every condition the assigner says is a finding in its own bucket, under
// `<scope>.<id>.<kind>`, written at the raise and deleted at the clear, and only as a finding: the keeper is the one
// source since the controller's end (novox/hq ADR 0590 §3, issue 1126 B8). Said straight to the router only where the
@@ -291,9 +229,6 @@ func saidConditionsAreFindings(t *testing.T) {
raised, cleared oc.Condition
key string
}{
{HeldCondition("mail", fNew, "ace", "refused", true, true), LiftedCondition("mail", fNew), "module.mail." + strings.TrimPrefix(fNew, meshcatalogclient.SourcePrefix2) + ".held"},
{NodeFailedCondition("ace", "mail", fNew, NodeFailure{Words: "x", Others: []string{"g14"}}, true), NodeFailedCondition("ace", "mail", fNew, NodeFailure{}, false), "module.ace.mail.failed-alone"},
{NeitherCondition("ace", "mail", Holding{Rule: 3, Words: "w"}, true), NeitherCondition("ace", "mail", Holding{}, false), "module.ace.mail.neither"},
{SeatWaitsCondition([]string{"assignments"}), SeatWaitsCondition(nil), "module.mesh-delivery-assigner.seat-states"},
{BackupCondition("ace", "mail", fNew, "disk full", true), BackupCondition("ace", "mail", fNew, "", false), "module.ace.mail." + strings.TrimPrefix(fNew, meshcatalogclient.SourcePrefix2) + ".backup"},
} {
@@ -336,8 +271,7 @@ func TestTheRecordAndBackupAsksAreValid(t *testing.T) {
if err != nil {
t.Fatal(err)
}
dgst := "sha256:" + strings.Repeat("b", 64)
b := BackupAsk(bkey, "ace", "mail", fNew, dgst, "no space left", 0, now)
b := BackupAsk(bkey, "ace", "mail", fNew, "no space left", 0, now)
vkey, err := asks.RevertAskKey("ace", "mail", fNew)
if err != nil {
t.Fatal(err)
@@ -360,18 +294,15 @@ func TestTheRecordAndBackupAsksAreValid(t *testing.T) {
if !strings.Contains(mustAsk(t, b).Explanation, "no space left") || mustAsk(t, b).Options[0].ID != mwc.BackupAgain || mustAsk(t, b).Options[1].ID != mwc.BackupSkip {
t.Errorf("the backup ask = %+v", mustAsk(t, b))
}
// the id binds the ask to the composition and to its number (review round 1, items 3 and 4)
if again := BackupAsk(bkey, "ace", "mail", fNew, dgst, "x", NextBackupAsking(0), now); mustAsk(t, again).ID == mustAsk(t, b).ID {
// the id binds the ask to its number (review round 1, item 4); its key binds it to the build (design 47 H §750: a want names no composition)
if again := BackupAsk(bkey, "ace", "mail", fNew, "x", NextBackupAsking(0), now); mustAsk(t, again).ID == mustAsk(t, b).ID {
t.Errorf("asked again under the same id")
}
if NextBackupAsking(-1) != 0 || NextBackupAsking(0) != 2 || NextBackupAsking(2) != 3 {
t.Errorf("the numbers of the askings: %d %d %d", NextBackupAsking(-1), NextBackupAsking(0), NextBackupAsking(2))
}
if BackupAskDigest(b) != ShortDigest(dgst) || ShortDigest(dgst) == dgst {
t.Errorf("the ask names composition %q, want %q", BackupAskDigest(b), ShortDigest(dgst))
}
// novox 2026-11-16: the router refuses a long hexadecimal string, so no word of an ask carries a digest or fingerprint whole.
held := BackupAsk(bkey, "novox", "mail", fNew, dgst, "the kept data between "+fNew+" and "+fNew+" is not known", 0, now)
held := BackupAsk(bkey, "novox", "mail", fNew, "the kept data between "+fNew+" and "+fNew+" is not known", 0, now)
if a := mustAsk(t, held); regexp.MustCompile(`[0-9a-f]{20,}`).MatchString(a.Headline + a.Explanation + a.Details) {
t.Errorf("the ask carries a long hexadecimal string: %q", a.Explanation)
}
@@ -401,6 +332,7 @@ func TestTheRecordAndBackupAsksAreValid(t *testing.T) {
// ADR 0546 clauses 7 and 8: a put's ask is valid at the record ask's key; for the bus its yes approves and binds the act,
// so the view cannot answer it, and it lasts no longer than an approving ask may.
put := puts.Put{FP: fNew, Why: "the bus's user list", Hold: true}
dgst := "sha256:" + strings.Repeat("b", 64)
d := ComposedDigest{Digest: dgst, Judgement: JudgedCannot, Words: "the have names no composition"}
for _, bus := range []bool{false, true} {
a, err := PutAsk(rkey, "ace", "mail", put, d, bus, now)
@@ -445,22 +377,6 @@ func TestTheRecordAndBackupAsksAreValid(t *testing.T) {
}
}
// 1945/AC21: the condition of a module on neither list is urgent, names the module, the node and the rule holding its want back,
// under the assigner's own name keyed by node and module, and is cleared under the same key.
func TestTheNeitherConditionNamesModuleNodeAndRule(t *testing.T) {
c := NeitherCondition("g14", "i3status-rust", Holding{Rule: mwc.RuleProviders, Words: "no provider of x11-display runs healthy on g14 or at its canary"}, true)
if _, err := occ.EncodeCondition(c); err != nil {
t.Fatalf("the condition is refused: %v", err)
}
if c.State != occ.StateRaised || c.Severity != occ.SeverityUrgent || c.Subject.ID != "i3status-rust" || c.Subject.Machine != "g14" ||
!strings.Contains(c.Explanation, "x11-display") || !strings.Contains(c.Explanation, "rule 5") || c.Key != "mesh-delivery-assigner.neither.g14.i3status-rust" {
t.Errorf("condition = %+v", c)
}
if got := NeitherCondition("g14", "i3status-rust", Holding{}, false); got.State != occ.StateCleared || got.Key != c.Key {
t.Errorf("cleared = %+v", got)
}
}
// mustAsk is the router's ask an asks-state value carries.
func mustAsk(t *testing.T, a asks.Ask) oc.Ask {
t.Helper()
@@ -154,18 +154,3 @@ func (f Findings) Say(say func(oc.Condition) error) func(oc.Condition) error {
return errors.Join(errs...)
}
}
// KindActingCycle is the finding of a want held on a cycle of acting waits no rule breaks (design 47 G A-323, A-330): scope module,
// id `<node>.<module>` of the held want, naming the cycle with each edge's step; cleared by the next pass that finds it held on no
// cycle.
const KindActingCycle = "acting-cycle"
// ActingCycleFinding is the finding acting-cycle of module's want on node, held on cycle.
func ActingCycleFinding(node, module, cycle string) Observed {
return Observed{Scope: mcc.ScopeModule, ID: node + "." + module, Kind: KindActingCycle, Machine: node, Severity: "warning",
Summary: fmt.Sprintf("the want of %s on %s is held on a cycle of acting waits: %s", module, node, cycle),
Headline: fmt.Sprintf("%s on %s waits on a cycle of acting parts", module, node),
Explanation: fmt.Sprintf("Each acting part on the cycle %s waits for another's new version to run, so none moves by itself. "+
"assigner_release lets one move with the version running.", cycle),
Source: "assigner." + KindActingCycle}
}
@@ -6,13 +6,11 @@ import (
"mesh-delivery-assigner/internal/assignment"
"mesh-delivery-assigner/internal/buckets"
"sort"
"strings"
"time"
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"
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
"git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
@@ -48,66 +46,15 @@ func PolicyOf(m catalogue.Manifest, chosen map[string]catalogue.PersonPolicy) (p
return catalogue.Upgrade(m, c)
}
func contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// KindProvisionFailed is the assigner's finding of a provision its module's want waits for that failed (ADR 0570 §4).
const KindProvisionFailed = "provision-failed"
// ProvisionFailedKey is a failed provision's finding's key, `provider.<node>.<consumer>.<provision>[.<local>].provision-failed`.
func ProvisionFailedKey(key string) string {
return mcc.Key(mcc.ScopeProvider, key, KindProvisionFailed)
}
// ProvisionFailedFinding is the finding of a failed provision, naming its consumer, its provider and why.
func ProvisionFailedFinding(key string, p meshprovisionerclient.Provision, at time.Time) (mcseat.Finding, error) {
summary := fmt.Sprintf("%s for %s on %s failed at %s on %s: %s, so %s is not moved there until it is provided", p.Provision,
p.Consumer.Module, p.Consumer.Node, p.Provider.Module, p.Provider.Node, p.Why, p.Consumer.Module)
return encode(Observed{Scope: mcc.ScopeProvider, ID: key, Kind: KindProvisionFailed, Machine: p.Consumer.Node, Also: also(p.Provider.Node, p.Consumer.Node),
Summary: summary, Said: p.Why, Headline: clipHeadline(p.Consumer.Module + " waits for a provision that failed"),
Explanation: occ.NothingToDo + " " + summary + ". It clears once the provider provides it.",
Source: "assigner." + KindProvisionFailed}, at)
}
// encode is the observation as the assigner's finding at at.
func encode(o Observed, at time.Time) (mcseat.Finding, error) { return o.Finding(at), nil }
func also(provider, consumer string) []string {
if provider == "" || provider == consumer {
return nil
}
return []string{provider}
}
// KindProvisionMissing is the assigner's finding of a required provision that has had no key for longer than its bound.
const KindProvisionMissing = "provision-missing"
// ProvisionMissingKey is its key, `provider.<node>.<module>.<provision>.provision-missing`.
func ProvisionMissingKey(key string) string {
return mcc.Key(mcc.ScopeProvider, key, KindProvisionMissing)
}
// ProvisionMissingFinding is the finding of a required provision with no key past bound (key `<node>.<module>.<provision>`).
func ProvisionMissingFinding(key string, bound time.Duration, at time.Time) (mcseat.Finding, error) {
parts := strings.SplitN(key, ".", 3)
if len(parts) != 3 {
return mcseat.Finding{}, fmt.Errorf("%q is not <node>.<module>.<provision>", key)
}
node, module, provision := parts[0], parts[1], parts[2]
summary := fmt.Sprintf("%s on %s requires %s and mesh-provisioner has composed no key for it in %s, so %s is not moved there: "+
"no provider of it may be placed", module, node, provision, bound, module)
return encode(Observed{Scope: mcc.ScopeProvider, ID: key, Kind: KindProvisionMissing, Machine: node,
Summary: summary, Headline: clipHeadline(module + " on " + node + " lacks " + provision),
Explanation: occ.NothingToDo + " " + summary + ". It clears once the provision has its key.",
Source: "assigner." + KindProvisionMissing}, at)
}
// KindUnplaced is, from the lease write, a node that runs but no assignments names (ADR 0571 §6).
const KindUnplaced = "unplaced"
@@ -212,9 +212,9 @@ func needsPerson(w PutWorld, d ComposedDigest) bool {
return d.Judgement == JudgedRecreates || d.Judgement == JudgedMovesData || d.Judgement == JudgedCannot
}
// PutWant is the want a put writes once it is wanted: the fingerprint and composition, marked put, and held when it holds.
// PutWant is the want a put writes once it is wanted: the fingerprint, marked put, and held when it holds.
func PutWant(p puts.Put) mwc.Want {
return mwc.Want{Fp: p.FP, Composed: p.Composed, Put: true, Hold: p.Hold, Words: "put: " + p.Why}
return mwc.Want{Fp: p.FP, 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
@@ -0,0 +1,46 @@
package assign
import (
"fmt"
"strings"
"time"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-sdk/go/views"
)
// KindAssignmentUnlisted is a module assigned to a node that no watched branch lists, left out of that node's composition
// (design 47 H-A-148, H-A-149): scope delivery, id `<node>.<module>`, severity warning.
const (
KindAssignmentUnlisted = "assignment-unlisted"
ScopeAssignmentUnlisted = "delivery"
)
// UnlistedKey is its finding's key, `delivery.<node>.<module>.assignment-unlisted`.
func UnlistedKey(node, module string) string {
return views.FindingKey(ScopeAssignmentUnlisted, KeyID(node+"."+module), KindAssignmentUnlisted)
}
// UnlistedOfKey is the node and module of an assignment-unlisted finding's key, or false for another finding's.
func UnlistedOfKey(key string) (node, module string, ok bool) {
rest, ok := strings.CutPrefix(key, ScopeAssignmentUnlisted+".")
if !ok {
return "", "", false
}
if rest, ok = strings.CutSuffix(rest, "."+KindAssignmentUnlisted); !ok {
return "", "", false
}
node, module, ok = strings.Cut(rest, ".")
return node, module, ok && node != "" && module != "" && !strings.Contains(module, ".")
}
// UnlistedFinding is the finding of module assigned to node and listed on none of its watched branches, raised by the composition
// step that leaves the assignment out (H-A-149).
func UnlistedFinding(node, module string, at time.Time) (mcseat.Finding, error) {
summary := fmt.Sprintf("%s is assigned %s, which no watched branch lists, so its composition leaves the assignment out", node, module)
return encode(Observed{Scope: ScopeAssignmentUnlisted, ID: node + "." + module, Kind: KindAssignmentUnlisted, Machine: node,
Severity: mcseat.FindingSeverityWarning, Summary: summary, Headline: clipHeadline(module + " on " + node + " is listed nowhere"),
Explanation: summary + ": a stale assignment is a fault of the assignments, not of the change judged (ADR 0578 §2). " +
"Take it off, or register the module on a watched branch.",
Source: "assigner." + KindAssignmentUnlisted}, at)
}
@@ -1,38 +0,0 @@
package assign
import (
"slices"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph"
)
// verbWaiting says why the module's want on node waits for a verb it invokes (novox/hq ADR 0614 §2): the first seat verb or
// module tool of Invokes (the module graph's verb edges, those it leaves out on a cycle not among them, §3) that no
// running healthy build serves. Nil Served (nothing read of what runs) waits for none, and a verb a running build serves
// already adds no wait. It holds under the provisions' rule (RuleProvisions): no reader knows a rule number of its own
// yet, so the words name the edge (graph.VerbWaitWords, which the delivery view reads).
func (m Module) verbWaiting(node string) (string, bool) {
if m.Served == nil {
return "", false
}
for _, v := range slices.Sorted(slices.Values(m.Invokes)) {
if !m.Served(v) {
return graph.VerbWaitWords(v, m.Name, node), true
}
}
return "", false
}
// busStateWaiting says why the module's want on node waits for bus state (ADR 0614 §5): its manifest asks bus state (a
// bus-state entry, as the module graph reads it) and no build whose manifest offers bus-state runs healthy on a node
// present. The provision bus-state is answered with no credential of a consumer's own, so ADR 0603 §5 counts the
// provider's own have and no provisioner key is waited for, handed or not. Nil Offering (nothing read of what runs) waits
// for none, and neither does a module that offers bus-state itself. It holds under the provisions' rule, its words naming bus state (graph.BusStateWaitWords).
func (m Module) busStateWaiting(node string) (string, bool) {
if len(m.Manifest.BusState) == 0 || m.Offering == nil || m.Offering(graph.BusState) ||
slices.Contains(m.Manifest.Offers(), graph.BusState) { // the bus module offering it waits on nobody for it
return "", false
}
return graph.BusStateWaitWords(m.Name, node), true
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -53,9 +53,6 @@ type Computed struct {
// Uncomputed is each placed module whose entry could not be computed, as "<node>/<module>: why", sorted: it is said,
// never left out in silence.
Uncomputed []string
// Cycles are the cycles among the acting waits, within one step or across steps (Cycles, design 47 G §272, A-323): said, never
// left in silence.
Cycles []string
}
// placedAt is one placed module with what its entry is computed from.
@@ -74,7 +71,7 @@ type placedAt struct {
optional func(string) bool
}
type actingRule struct{ seat, step, on, bound string }
type actingRule struct{ seat, step, on string }
// Compute is the assignment graph revision of in: one entry per module placed on a node whose branch's catalog graph
// holds it, its version the build the placement names or else the catalog entry's fingerprint (design 47 lines 909-914),
@@ -128,7 +125,7 @@ func Compute(in Inputs) Computed {
p.langs[lang] = true
}
for _, r := range ce.Acts {
p.acts = append(p.acts, actingRule{seat: r.Seat, step: r.Step, on: r.On, bound: r.Bound})
p.acts = append(p.acts, actingRule{seat: r.Seat, step: r.Step, on: r.On})
}
p.provides, p.contributes = ce.Provides, ce.Contributes
p.delivering = map[string]seatdef.Definition{}
@@ -199,7 +196,7 @@ func Compute(in Inputs) Computed {
}
for _, h := range from {
t.entry.Edges = append(t.entry.Edges, meshwants.Edge{Kind: EdgeActing, Node: h.node, Module: part, Fp: h.entry.Fp,
Seat: rule.seat, Step: rule.step, Bound: rule.bound})
Seat: rule.seat, Step: rule.step})
}
}
}
@@ -217,7 +214,6 @@ func Compute(in Inputs) Computed {
rev.Entries = append(rev.Entries, meshwants.NodeEntryRef{Node: p.node, Module: p.placed.Module, Digest: d})
}
out.Revision = rev
out.Cycles = Cycles(slices.Collect(maps.Values(out.Entries)))
slices.Sort(out.Uncomputed)
return out
}
@@ -229,7 +225,7 @@ func sortEdges(edges []meshwants.Edge) {
}
func edgeKey(e meshwants.Edge) string {
return strings.Join([]string{e.Kind, e.Node, e.Module, e.Provision, e.Seat, e.Step, e.Fp, e.Bound}, "\x00")
return strings.Join([]string{e.Kind, e.Node, e.Module, e.Provision, e.Seat, e.Step, e.Fp}, "\x00")
}
// EntryDigest is the digest an entry is stored under: the same entry, the same digest.
@@ -1,248 +0,0 @@
package assigngraph
import (
"fmt"
"maps"
"slices"
"strings"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"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"
)
// Cycles are the cycles among the acting waits (design 47 G §272, ADR 0656, A-323): an entry waits for its acting parts in the step
// an edge names, so acting parts that wait for each other, in one step or across steps, wait for ever unless a rule breaks the
// cycle. A cycle within one step is `<step>: a -> b -> a`; one across steps names each edge's step, `a -[compose]-> b -[place]-> a`;
// each by node and module, said once from its smallest member, sorted. A holder's own inputs are no edge here (the graph gives an
// acting edge only from a part to the entries it acts on, never to what the part is built from).
func Cycles(entries []meshwants.AssignmentEntry) []string {
type key struct{ step, at string }
next := map[key][]string{}
steps := map[string]bool{}
for _, e := range entries {
for _, edge := range e.Edges {
if edge.Kind != EdgeActing {
continue
}
k := key{edge.Step, e.Node + "/" + e.Module}
next[k] = append(next[k], edge.Node+"/"+edge.Module)
steps[edge.Step] = true
}
}
var out []string
for _, step := range slices.Sorted(maps.Keys(steps)) {
const (
open = iota + 1
done
)
state := map[string]int{}
var path []string
var walk func(at string)
walk = func(at string) {
state[at] = open
path = append(path, at)
for _, to := range next[key{step, at}] {
switch state[to] {
case 0:
walk(to)
case open:
from := slices.Index(path, to)
cycle := slices.Clone(path[from:])
// start at the smallest member so one cycle is said once, whichever member is met first
lowest := slices.Index(cycle, slices.Min(cycle))
cycle = append(cycle[lowest:], cycle[:lowest]...)
out = append(out, fmt.Sprintf("%s: %s -> %s", step, strings.Join(cycle, " -> "), cycle[0]))
}
}
path = path[:len(path)-1]
state[at] = done
}
starts := map[string]bool{}
for k := range next {
if k.step == step {
starts[k.at] = true
}
}
for _, at := range slices.Sorted(maps.Keys(starts)) {
if state[at] == 0 {
walk(at)
}
}
}
// Across steps (A-323): the shortest cycle through each entry over every acting edge, said when its edges name two steps or more.
for _, hops := range cyclesThrough(entries, func(_ meshwants.AssignmentEntry, e meshwants.Edge) bool { return e.Kind == EdgeActing }) {
if crossesSteps(hops) {
out = append(out, hopWords(rotated(hops)))
}
}
slices.Sort(out)
return slices.Compact(out)
}
// HeldCycles is, by `<node>/<module>`, the cycle each entry lies on among the edges holds says hold it (A-323, A-330): a want held
// on such a cycle is held for ever, since no rule breaks it. Each cycle starts at the entry and names each edge's step.
func HeldCycles(entries []meshwants.AssignmentEntry, holds func(e meshwants.AssignmentEntry, edge meshwants.Edge) bool) map[string]string {
out := map[string]string{}
for at, hops := range cyclesThrough(entries, holds) {
out[at] = hopWords(hops)
}
return out
}
// Engines is, by node, the module that holds the seat node-engine there, read from the acting edges' seat (A-330).
func Engines(entries []meshwants.AssignmentEntry) map[string]string {
out := map[string]string{}
for _, e := range entries {
for _, edge := range e.Edges {
if edge.Kind == EdgeActing && edge.Seat == nodeengine.Seat {
out[edge.Node] = edge.Module
}
}
}
return out
}
// Runner is the module that holds the seat mesh-pipeline-runner, read from the acting edges' seat as Engines reads the node-engine
// (A-334); "" when none is read.
func Runner(entries []meshwants.AssignmentEntry) string {
for _, e := range entries {
for _, edge := range e.Edges {
if edge.Kind == EdgeActing && edge.Seat == meshpipelinerunner.Seat {
return edge.Module
}
}
}
return ""
}
// hop is one edge of a cycle: from the entry at, in step, to the next hop's entry.
type hop struct{ at, step string }
// cyclesThrough is, by `<node>/<module>`, the shortest cycle through each entry over the edges keep takes, found within the
// entry's strongly connected part, each starting at the entry.
func cyclesThrough(entries []meshwants.AssignmentEntry, keep func(meshwants.AssignmentEntry, meshwants.Edge) bool) map[string][]hop {
type out struct{ to, step string }
next := map[string][]out{}
for _, e := range entries {
at := e.Node + "/" + e.Module
for _, edge := range e.Edges {
if keep(e, edge) {
next[at] = append(next[at], out{edge.Node + "/" + edge.Module, edge.Step})
}
}
}
for at := range next {
slices.SortFunc(next[at], func(a, b out) int { return strings.Compare(a.to+"\x00"+a.step, b.to+"\x00"+b.step) })
}
part := strongParts(slices.Sorted(maps.Keys(next)), func(at string) []string {
var to []string
for _, o := range next[at] {
to = append(to, o.to)
}
return to
})
found := map[string][]hop{}
for _, start := range slices.Sorted(maps.Keys(next)) {
// breadth first from start back to it, within its part
prev := map[string]hop{}
queue := []string{start}
seen := map[string]bool{}
for len(queue) > 0 && found[start] == nil {
at := queue[0]
queue = queue[1:]
for _, o := range next[at] {
if part[o.to] != part[start] {
continue
}
if o.to == start {
hops := []hop{{at, o.step}}
for cur := at; cur != start; {
h := prev[cur]
hops = append(hops, h)
cur = h.at
}
slices.Reverse(hops)
found[start] = hops
break
}
if !seen[o.to] {
seen[o.to] = true
prev[o.to] = hop{at, o.step}
queue = append(queue, o.to)
}
}
}
}
return found
}
// strongParts numbers each vertex by its strongly connected part (Tarjan).
func strongParts(vertices []string, succ func(string) []string) map[string]int {
index, low, part := map[string]int{}, map[string]int{}, map[string]int{}
on := map[string]bool{}
var stack []string
n, parts := 0, 0
var visit func(v string)
visit = func(v string) {
index[v], low[v] = n, n
n++
stack = append(stack, v)
on[v] = true
for _, w := range succ(v) {
if _, ok := index[w]; !ok {
visit(w)
low[v] = min(low[v], low[w])
} else if on[w] {
low[v] = min(low[v], index[w])
}
}
if low[v] == index[v] {
parts++
for {
w := stack[len(stack)-1]
stack = stack[:len(stack)-1]
on[w] = false
part[w] = parts
if w == v {
break
}
}
}
}
for _, v := range vertices {
if _, ok := index[v]; !ok {
visit(v)
}
}
return part
}
func crossesSteps(hops []hop) bool {
for _, h := range hops[1:] {
if h.step != hops[0].step {
return true
}
}
return false
}
// rotated is the cycle started at its smallest member, so one cycle is said once.
func rotated(hops []hop) []hop {
lowest := 0
for i, h := range hops {
if h.at < hops[lowest].at {
lowest = i
}
}
return append(slices.Clone(hops[lowest:]), hops[:lowest]...)
}
// hopWords is a cycle with each edge's step: `a -[compose]-> b -[place]-> a`.
func hopWords(hops []hop) string {
var b strings.Builder
for _, h := range hops {
fmt.Fprintf(&b, "%s -[%s]-> ", h.at, h.step)
}
return b.String() + hops[0].at
}
@@ -1,60 +0,0 @@
package assigngraph
import (
"slices"
"testing"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
)
// Design 47 G §272 (AS10), A-323: a cycle among the waits is found within one step and across steps, each edge's step named across
// steps; a chain and provisioning edges are none.
func TestACycleAmongTheWaitsWithinOrAcrossStepsIsFound(t *testing.T) {
act := func(node, module, step string) meshwants.Edge {
return meshwants.Edge{Kind: EdgeActing, Node: node, Module: module, Step: step}
}
entry := func(module string, edges ...meshwants.Edge) meshwants.AssignmentEntry {
return meshwants.AssignmentEntry{Node: "ace", Module: module, Edges: edges}
}
for _, c := range []struct {
name string
entries []meshwants.AssignmentEntry
want []string
}{
{"two parts on each other in one step", []meshwants.AssignmentEntry{entry("a", act("ace", "b", "compose")), entry("b", act("ace", "a", "compose"))},
[]string{"compose: ace/a -> ace/b -> ace/a"}},
{"three in a ring, said once", []meshwants.AssignmentEntry{entry("c", act("ace", "a", "build")), entry("a", act("ace", "b", "build")), entry("b", act("ace", "c", "build"))},
[]string{"build: ace/a -> ace/b -> ace/c -> ace/a"}},
{"the indexer taking in the checker, the checker checking the indexer", []meshwants.AssignmentEntry{entry("checker", act("ace", "indexer", "take-in")), entry("indexer", act("ace", "checker", "check"))},
[]string{"ace/checker -[take-in]-> ace/indexer -[check]-> ace/checker"}},
{"the assigner and the node-engine, across compose and place", []meshwants.AssignmentEntry{entry("assigner", act("ace", "engine", "compose")),
entry("engine", act("ace", "assigner", "place")), entry("app", act("ace", "engine", "compose"), act("ace", "assigner", "place"))},
[]string{"ace/assigner -[compose]-> ace/engine -[place]-> ace/assigner"}},
{"a chain", []meshwants.AssignmentEntry{entry("a", act("ace", "b", "compose")), entry("b", act("ace", "c", "compose")), entry("c")}, nil},
{"provisioning edges are no wait of a step", []meshwants.AssignmentEntry{entry("a", meshwants.Edge{Kind: EdgeProvisioning, Node: "ace", Module: "b"}), entry("b", meshwants.Edge{Kind: EdgeProvisioning, Node: "ace", Module: "a"})}, nil},
} {
if got := Cycles(c.entries); !slices.Equal(got, c.want) {
t.Errorf("%s: cycles %v, want %v", c.name, got, c.want)
}
}
}
// A-323, A-330: the node-engine on a node is read from the acting edges' seat, and the cycles that hold a want are those of the
// edges said to hold it, each from the entry, naming each edge's step.
func TestTheHeldCyclesAreThoseOfTheHoldingEdges(t *testing.T) {
entries := []meshwants.AssignmentEntry{
{Node: "ace", Module: "assigner", Edges: []meshwants.Edge{{Kind: EdgeActing, Node: "ace", Module: "engine", Step: "compose", Seat: "node-engine"}}},
{Node: "ace", Module: "engine", Edges: []meshwants.Edge{{Kind: EdgeActing, Node: "ace", Module: "assigner", Step: "place", Seat: "mesh-wants"}}},
}
if got := Engines(entries); len(got) != 1 || got["ace"] != "engine" {
t.Errorf("the node-engines %v, want engine on ace", got)
}
all := func(meshwants.AssignmentEntry, meshwants.Edge) bool { return true }
if got := HeldCycles(entries, all); len(got) != 2 || got["ace/engine"] != "ace/engine -[place]-> ace/assigner -[compose]-> ace/engine" {
t.Errorf("held cycles %v", got)
}
// the node-engine's want held by no acting edge: no cycle holds anything
if got := HeldCycles(entries, func(e meshwants.AssignmentEntry, _ meshwants.Edge) bool { return e.Module != "engine" }); len(got) != 0 {
t.Errorf("held cycles with the node-engine's edges holding nothing: %v", got)
}
}
@@ -86,7 +86,7 @@ func TestTheAssignmentGraphIsComputedFromItsInputsAndKept(t *testing.T) {
}
want := []meshwants.Edge{
{Kind: EdgeActing, Node: "anchor", Module: "build-go", Fp: "src2:b1", Seat: "node-build-go", Step: "build"},
{Kind: EdgeActing, Node: "anchor", Module: "node-engine", Fp: "src2:e1", Seat: "node-engine", Step: "compose", Bound: "30m"},
{Kind: EdgeActing, Node: "anchor", Module: "node-engine", Fp: "src2:e1", Seat: "node-engine", Step: "compose"}, // the edge stays; the wait's bound goes (H-A-70)
{Kind: EdgeProvisioning, Node: "anchor", Module: "postgres", Fp: "src2:p1", Provision: "database"},
}
if fmt.Sprint(webA.Edges) != fmt.Sprint(want) {
@@ -18,12 +18,6 @@ import (
const (
// WaitsState holds the waits on an outside cause, one key `<node>.<module>.<fingerprint hex>` (design 47 G §706).
WaitsState = "waits"
// DeliveredAgainState holds each ask of assigner_delivered_again, one key `<module>`, its value the version, who asked and why, and
// why it does not hold yet (design 47 G §376, A-250).
DeliveredAgainState = "delivered-again"
// DeliveryWaitsState holds each dependent's delivery wait the assigner said, one key `<module>`, its value the wait-held said
// (design 47 G §376, §498, A-246).
DeliveryWaitsState = "delivery-waits"
// PutWaitsState holds each put wait the assigner said, one key `<node>.<module>`, its value the wait's id and the put as said
// (design 47 G A-204, A-211), so a put that ends while the assigner is stopped gets its wait-ended at the next start.
PutWaitsState = "put-waits"
@@ -45,8 +39,6 @@ func Differences() string { return own(wants.StateDifferences) }
func Asks() string { return own("asks") }
func Puts() string { return own("puts") }
func Waits() string { return own(WaitsState) }
func DeliveredAgain() string { return own(DeliveredAgainState) }
func DeliveryWaits() string { return own(DeliveryWaitsState) }
func PutWaits() string { return own(PutWaitsState) }
func Inputs() string { return own(InputsState) }
func CompositionRuns() string { return own(CompositionRunsState) }
@@ -71,10 +63,6 @@ const (
Graph = IndexerModule + "_graph"
ModulesRead = IndexerModule + "." + catalog.StateModules
ManifestsRead = IndexerModule + "." + catalog.StateManifests
// ProvisionerModule is the holder of the seat mesh-provisioner, named from this module's manifest (reads its provisions); Provisions
// is its state provisions.
ProvisionerModule = "mesh-provisioner"
Provisions = ProvisionerModule + "_provisions"
// TellerModule is the module whose hand the operator's answers pass: the one that holds each ask's answer, and the
// name the hand-act log records a warrant under. Held equal to the manifest's reads by its test.
TellerModule = "mesh-delivery-teller"
@@ -12,9 +12,9 @@ func TestBucketsAreTheEarlierNames(t *testing.T) {
for name, c := range map[string][2]string{
"Have": {Have, "node-engine_have"}, "ComposedRead": {ComposedRead, "mesh-host.composed"},
"Modules": {Modules, "mesh-delivery-indexer_modules"}, "Manifests": {Manifests, "mesh-delivery-indexer_manifests"},
"Answers": {Answers, "mesh-delivery-teller_answers"},
"Grants": {Grants, "mesh-grants_grants"},
"Provisions": {Provisions, "mesh-provisioner_provisions"}, "TellerModule": {TellerModule, "mesh-delivery-teller"},
"Answers": {Answers, "mesh-delivery-teller_answers"},
"Grants": {Grants, "mesh-grants_grants"},
"TellerModule": {TellerModule, "mesh-delivery-teller"},
} {
if c[0] != c[1] {
t.Errorf("%s = %q, want %q", name, c[0], c[1])
@@ -9,7 +9,6 @@ import (
"encoding/json"
"fmt"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mdcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient"
"reflect"
"slices"
"sort"
@@ -170,11 +169,11 @@ func JudgeAnswers(p mma.Proposal, intended map[string]map[string]bool, answers m
}
switch {
case len(v.Fails) > 0:
v.State = mdcc.VerdictFail
v.State = plc.VerdictFail
case len(waiting) > 0:
v.State = plc.VerdictWaits
default:
v.State = mdcc.VerdictPass
v.State = plc.VerdictPass
}
return v
}
@@ -2,7 +2,6 @@ package judge
import (
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
mdcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient"
"slices"
"strings"
"testing"
@@ -49,22 +48,22 @@ func TestJudge(t *testing.T) {
words string
marked string
}{
{"all the same", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": same(8)}, nil, mdcc.VerdictPass, "", ""},
{"all the same", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": same(8)}, nil, plc.VerdictPass, "", ""},
{"a module added where intended", false, map[string]*nodeengine.CandidateAnswer{"anchor": {Proposal: "p-one", Revision: 7, Verdict: nodeengine.CandidateAnswerVerdictDiffers,
Added: []nodeengine.CandidateAdded{{Module: "web", Unissued: []string{"its own secret"}}}}, "laptop": same(8)}, nil, mdcc.VerdictPass, "", ""},
{"a difference not computed passes, marked", false, map[string]*nodeengine.CandidateAnswer{"anchor": differs(7, "mail"), "laptop": same(8)}, nil, mdcc.VerdictPass, "", "mail"},
Added: []nodeengine.CandidateAdded{{Module: "web", Unissued: []string{"its own secret"}}}}, "laptop": same(8)}, nil, plc.VerdictPass, "", ""},
{"a difference not computed passes, marked", false, map[string]*nodeengine.CandidateAnswer{"anchor": differs(7, "mail"), "laptop": same(8)}, nil, plc.VerdictPass, "", "mail"},
{"the seed carries a difference, named", true, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": {Proposal: "p-one", Revision: 8,
Verdict: nodeengine.CandidateAnswerVerdictDiffers, Differs: []nodeengine.CandidateDiffers{{Module: "node-tools", Resource: "node-tools.runtime", Why: "the resource differs",
Bodies: []nodeengine.CandidateBodies{{ID: "node-tools.runtime", Paths: []string{"env.MESH_OWNED_PATHS./etc/resolv.conf", "env.MESH_TOOL_MODULES"},
Running: `{"env":{"MESH_OWNED_PATHS":"{\"/etc/hosts\":\"hostname\",\"/etc/resolv.conf\":\"networkmanager (node-uplink)\"}"}}`,
Composed: `{"env":{"MESH_OWNED_PATHS":"{\"/etc/hosts\":\"hostname\",\"/etc/resolv.conf\":\"systemd-resolved (node-resolver)\"}","MESH_TOOL_MODULES":"… (cut at 8192 bytes)`}}}}}}, nil, mdcc.VerdictPass, "", ""},
Composed: `{"env":{"MESH_OWNED_PATHS":"{\"/etc/hosts\":\"hostname\",\"/etc/resolv.conf\":\"systemd-resolved (node-resolver)\"}","MESH_TOOL_MODULES":"… (cut at 8192 bytes)`}}}}}}, nil, plc.VerdictPass, "", ""},
{"a refusal", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": {Proposal: "p-one", Revision: 8, Verdict: nodeengine.CandidateAnswerVerdictRefused,
Refusals: []nodeengine.CandidateRefusal{{Module: "web", Why: "no own secret"}}}}, nil, mdcc.VerdictFail, "laptop refuses", ""},
Refusals: []nodeengine.CandidateRefusal{{Module: "web", Why: "no own secret"}}}}, nil, plc.VerdictFail, "laptop refuses", ""},
{"a node not answering, within its bound", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7)}, map[string]bool{"laptop": true}, plc.VerdictWaits, "laptop (offline)", ""},
{"an answer of an earlier revision, past its bound, is no answer and decided without it", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(6), "laptop": same(8)}, nil, mdcc.VerdictPass, "no answer from anchor", ""},
{"an answer of an earlier revision, past its bound, is no answer and decided without it", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(6), "laptop": same(8)}, nil, plc.VerdictPass, "no answer from anchor", ""},
{"a module held as today passes, shown in the brief", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": {Proposal: "p-one", Revision: 8,
Verdict: nodeengine.CandidateAnswerVerdictSame, Held: []nodeengine.CandidateRefusal{{Module: "spiegel", Why: "a required value is unset"}}}}, nil, mdcc.VerdictPass, "", ""},
{"its later answer", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": same(8)}, nil, mdcc.VerdictPass, "", ""},
Verdict: nodeengine.CandidateAnswerVerdictSame, Held: []nodeengine.CandidateRefusal{{Module: "spiegel", Why: "a required value is unset"}}}}, nil, plc.VerdictPass, "", ""},
{"its later answer", false, map[string]*nodeengine.CandidateAnswer{"anchor": same(7), "laptop": same(8)}, nil, plc.VerdictPass, "", ""},
} {
q := p
q.Seed = row.seed
@@ -73,10 +72,10 @@ func TestJudge(t *testing.T) {
if v.State != row.state || !strings.Contains(all, row.words) {
t.Errorf("%s: %s, %q", row.name, v.State, all)
}
if row.seed && row.state == mdcc.VerdictPass && !strings.Contains(Brief(q, v), "the seed carries: node-tools: MESH_OWNED_PATHS[/etc/resolv.conf] networkmanager (node-uplink) → (value cut) (and 1 more fields)") {
if row.seed && row.state == plc.VerdictPass && !strings.Contains(Brief(q, v), "the seed carries: node-tools: MESH_OWNED_PATHS[/etc/resolv.conf] networkmanager (node-uplink) → (value cut) (and 1 more fields)") {
t.Errorf("%s: the brief does not name it: %s", row.name, Brief(q, v))
}
if row.seed && row.state == mdcc.VerdictPass {
if row.seed && row.state == plc.VerdictPass {
whole := row.answers["laptop"].Differs[0]
whole.Bodies = []nodeengine.CandidateBodies{{ID: "r", Paths: []string{"env.MESH_OWNED_PATHS./etc/resolv.conf"},
Running: `{"env":{"MESH_OWNED_PATHS":"{\"/etc/resolv.conf\":\"networkmanager (node-uplink)\"}"}}`,
@@ -87,21 +87,6 @@ func Causes(conds []Cond, m string, moved func(owner string) bool) []Cause {
return out
}
// OwnNetworkKey is the key of a machine's own open network condition, which holds the machine as a whole (§706 *M's own
// network*).
func OwnNetworkKey(m string) string { return "machine." + m + ".network" }
// OwnNetwork are the machines whose own network condition is open among conds.
func OwnNetwork(conds []Cond) map[string]bool {
out := map[string]bool{}
for _, c := range conds {
if p := strings.Split(c.Key, "."); len(p) == 3 && p[0] == "machine" && p[2] == "network" && c.Key == OwnNetworkKey(p[1]) {
out[p[1]] = true
}
}
return out
}
// Wait is one outside wait as the assigner keeps it: the move of Module at FP on Node, or its settle (Settling). Decided is
// what ended it for the rest of that fingerprint on that node: `go-on` (counted healthy by the operator's word) or `failed`
// (the delivery's failure), so a check that goes on failing is not waited on again.
@@ -31,9 +31,6 @@ func TestCauses(t *testing.T) {
if !slices.Equal(got, want) {
t.Errorf("causes = %v, want %v (a rewritten naming a moved module, an unreachable not listing ace and ace's own network are none)", got, want)
}
if own := OwnNetwork(conds); !own["ace"] || !own["hub2"] || own["hub"] {
t.Errorf("own network = %v", own)
}
}
func facts(now time.Time, conds ...Cond) Facts {
+19 -20
View File
@@ -50,14 +50,14 @@ func TestManifest(t *testing.T) {
// §431, §507: the gate's source is read through its verb `source` and its event `source-moved`, and no `merges` is read.
// A-175, A-178: the teller's answers are followed through its first view and its views family, never its bucket.
// §389: the watchman's machine-away and machine-back are consumed, never its presence.
want := []string{"mesh-grants.grants", "mesh-host.composed",
"mesh-provisioner.provisions", "node-engine.have"}
// A5/AC1 (design 47 H §750): no want waits for a provision, so the provisioner's provisions are no read; the grants stay
// for a put's own judgement (ADR 0546 clause 4).
want := []string{"mesh-grants.grants", "mesh-host.composed", "node-engine.have"}
if !reflect.DeepEqual(reads, want) {
t.Errorf("reads = %v, want exactly %v", reads, want)
}
// the buckets the program names are the manifest's reads, `<module>.<state>` as `<module>_<state>`
named := []string{buckets.Grants,
buckets.ComposedRead, "mesh-provisioner_provisions", buckets.Have}
named := []string{buckets.Grants, buckets.ComposedRead, buckets.Have}
slices.Sort(named)
for i, r := range want {
if got := strings.Replace(named[i], "_", ".", 1); got != r {
@@ -70,7 +70,7 @@ func TestManifest(t *testing.T) {
}
if want := map[string]int{"asks": 5, "differences": 64, "puts": 20, "wants": 20,
"assignments": 64, "placement": 64, "copies": 1, "proposals": 5, "candidates": 5, "pulses": 0, "findings": 5, "policies": 20, "seat-holders": 5, views.MarksState: 1, views.StatusState: 1,
"engine-reads": 1, "written": 5, "waits": 5, "put-waits": 1, "delivery-waits": 1, "delivered-again": 1, "inputs": 1, "composition-runs": 1, "pins": 5}; !reflect.DeepEqual(states, want) {
"engine-reads": 1, "written": 5, "waits": 5, "put-waits": 1, "inputs": 1, "composition-runs": 1}; !reflect.DeepEqual(states, want) {
t.Errorf("state = %v, want %v", states, want)
}
if _, ok := m.OwnSecrets["broker"]; !ok || len(m.OwnSecrets) != 1 {
@@ -105,21 +105,18 @@ func TestManifest(t *testing.T) {
// 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",
"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_pins", "assigner_unpin", "assigner_delivered_again"}) {
"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"}) {
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)
}
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)
}
// ADR 0621 §2: each first-view tool answers exactly its readers, never the assigner.
// Design 47 G §717: the teller and the status view take their first views of the seat mesh-wants' asks and wants, and of
// the assignments, from the tools named for the states.
callers := map[string]string{"assignments": "mesh-grants,node-tools,mesh-delivery-indexer,mesh-delivery-builder,mesh-delivery-checker,mesh-delivery-view",
"seat-holders": "node-tools,mesh-delivery-builder,mesh-delivery-view,mesh-delivery-teller,mesh-delivery-checker,mesh-delivery-indexer", "wants": "mesh-grants,mesh-delivery-view", "asks": "mesh-delivery-teller,mesh-delivery-view"}
env := m.Build.Artifacts[0].Env
for tool, list := range callers {
if env[views.CallersEnv(tool)] != list || views.ParseCallers(env[views.CallersEnv(tool)]).Allows("n1."+m.Module) {
t.Errorf("%s callers = %q, want %q", tool, env[views.CallersEnv(tool)], list)
// design 47 H §752, H-A-66: every first-view tool answers every caller, so the manifest names no callers list for any.
for _, a := range m.Build.Artifacts {
for k := range a.Env {
if strings.HasPrefix(k, "MESH_VIEW_CALLERS_") {
t.Errorf("the artifact %s names the callers list %s: no seat or tool keeps one (design 47 H §752)", a.Name, k)
}
}
}
// ADR 0635 §5: its views family is its ordinary events, `views.<state>` among its emits, on no stream of its own.
@@ -135,9 +132,10 @@ func TestManifest(t *testing.T) {
}
}
// ADR 0618 §4: and it hears each node's engine say its reads changed; ADR 0636 §4 (issue 1966): and the seat list's two events;
// issue 1966 note 151: and the teller's ask-ended, its subject the one the assigner hears; §376, §389: its own version-delivered and
// the watchman's machine-away and machine-back, read whole at its start.
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-wants.version-delivered", "mesh-watchdogs.machine-away", "mesh-watchdogs.machine-back", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", builds.BuilderModule + "." + builds.BuildsStreamEvents, buckets.IndexerModule + ".take-in.taken", buckets.TellerModule + "." + tellerevents.AskEnded, buckets.TellerModule + ".views." + buckets.AnswersState, "mesh-pipeline-runner.pipeline-ended", "mesh-pipeline-runner.group-ended", "node-build-go.step-ended", "node-build-go.ask-taken", "node-build-go.step-progress", "node-engine.manifest-reads-changed", "node-engine.running", "mesh-delivery.pinned", "mesh-delivery.freed", "mesh-delivery.heads-replaced", "mesh-delivery.pins-stated"}) {
// 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,
// 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"}) {
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",
@@ -151,7 +149,6 @@ func TestManifest(t *testing.T) {
"seat:node-build-go.drop", // §720, A-469s: a composition run past its bound drops its ask: the composition run's ask on the Go build seat's queue check (accept.check.<asker>)
"seat:node-build-go.output", // A-254: a composition run's answer kept as the build seat's object
"seat:node-engine.compose-candidate", // §354, A-226: each machine's composition input
"seat:node-engine.manifest-reads", // ADR 0618 §3
"seat:operator-channel.asks"}; !slices.Equal(slices.Sorted(slices.Values(m.Invokes)), want) { // ADR 0668 §4: the ended asks at bind
t.Errorf("invokes = %v, want %v", m.Invokes, want)
}
@@ -168,7 +165,7 @@ func TestManifest(t *testing.T) {
}
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) ||
raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 8 ||
raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 10 || 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-step-bound"].Default != "30m" || raw.Config["run-untaken-bound"].Default != "24h" || raw.Config["blame-tries"].Default != float64(20) {
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)
@@ -183,6 +180,8 @@ func TestManifest(t *testing.T) {
{"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_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_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+`"`) ||
!strings.Contains(string(file), `"content": "${config:`+f.key+`}"`) {
+38 -24
View File
@@ -34,7 +34,6 @@
"reads": [
"mesh-grants.grants",
"mesh-host.composed",
"mesh-provisioner.provisions",
"node-engine.have"
],
"uses": [
@@ -49,26 +48,19 @@
"mesh-catalog.registration-changed",
"mesh-delivery.source-moved",
"mesh-catalog.version-released",
"mesh-wants.version-delivered",
"mesh-watchdogs.machine-away",
"mesh-watchdogs.machine-back",
"mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed",
"mesh-delivery-builder.build.ended.**",
"mesh-delivery-indexer.take-in.taken",
"mesh-delivery-teller.ask-ended",
"mesh-delivery-teller.views.answers",
"mesh-pipeline-runner.pipeline-ended",
"mesh-pipeline-runner.group-ended",
"node-build-go.step-ended",
"node-build-go.ask-taken",
"node-build-go.step-progress",
"node-engine.manifest-reads-changed",
"node-engine.running",
"mesh-delivery.pinned",
"mesh-delivery.freed",
"mesh-delivery.heads-replaced",
"mesh-delivery.pins-stated"
"node-engine.running"
],
"invokes": [
"mesh-delivery-indexer.manifests",
@@ -88,7 +80,6 @@
"seat:node-build-go.output",
"seat:node-build-go.drop",
"seat:node-engine.compose-candidate",
"seat:node-engine.manifest-reads",
"seat:operator-channel.asks",
"seat:node-build-go.accept.check"
],
@@ -138,9 +129,7 @@
"assigner_ask_again",
"assigner_written",
"assigner_why",
"assigner_pins",
"assigner_unpin",
"assigner_delivered_again"
"assigner_want_drop"
],
"state": [
{ "name": "assignments", "history": 64 },
@@ -162,11 +151,8 @@
{ "name": "written", "history": 5 },
{ "name": "waits", "history": 5 },
{ "name": "put-waits", "history": 1 },
{ "name": "delivery-waits", "history": 1 },
{ "name": "delivered-again", "history": 1 },
{ "name": "inputs", "history": 1, "max-mib": 64 },
{ "name": "composition-runs", "history": 1, "key-ttl": true, "max-mib": 64 },
{ "name": "pins", "history": 5, "max-mib": 4 }
{ "name": "composition-runs", "history": 1, "key-ttl": true, "max-mib": 64 }
],
"config": {
"outside-wait-minutes": {
@@ -191,6 +177,22 @@
"trusted": false,
"default": "take-off,remove-node,stops"
},
"tier-bound": {
"type": "number",
"description": "minutes each tier of a pipeline's movers has to run on every present placing machine before the assigner writes the next tier's wants; a tier that does not run within it ends the delivery with the finding tier-late and writes no later tier (design 47 H section 751).",
"minimum": 1,
"maximum": 10080,
"trusted": false,
"default": 30
},
"entry-asks": {
"type": "number",
"description": "how often the assigner asks a catalog entry again, on each catalog-revision and when its link to the bus opens again, after its ask failed to reach the holder of the seat mesh-catalog; one more failure leaves it unanswered, with the finding entry-unanswered (design 47 H, H-A-60).",
"minimum": 1,
"maximum": 100,
"trusted": false,
"default": 5
},
"composition-runs-cap-mib": {
"type": "number",
"description": "the cap of the state composition-runs in MiB, the process refusing a new composition run at it with its steps ending could not run naming the fill (design 47 G section 719, A-469d); its maximum is the manifest's max-mib.",
@@ -273,6 +275,22 @@
"mode": "0600",
"content": "${config:ask-operator-for}"
},
{
"id": "tier-bound",
"type": "file",
"path": "${dir:state}/tier-bound",
"owner": "mesh-delivery-assigner",
"mode": "0600",
"content": "${config:tier-bound}"
},
{
"id": "entry-asks",
"type": "file",
"path": "${dir:state}/entry-asks",
"owner": "mesh-delivery-assigner",
"mode": "0600",
"content": "${config:entry-asks}"
},
{
"id": "composition-runs-cap-mib",
"type": "file",
@@ -326,6 +344,8 @@
"MESH_ASSIGNER_OUTSIDE_WAIT_FILE": "${dir:state}/outside-wait-minutes",
"MESH_ASSIGNER_OUTSIDE_SETTLE_FILE": "${dir:state}/outside-settle-seconds",
"MESH_ASSIGNER_ASK_OPERATOR_FOR_FILE": "${dir:state}/ask-operator-for",
"MESH_ASSIGNER_TIER_BOUND_FILE": "${dir:state}/tier-bound",
"MESH_ASSIGNER_ENTRY_ASKS_FILE": "${dir:state}/entry-asks",
"MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE": "${dir:state}/composition-runs-cap-mib",
"MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "${dir:state}/composition-runs-kept",
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "${dir:state}/composition-step-bound",
@@ -349,13 +369,7 @@
"binary": "mesh-delivery-assigner",
"loads": [
"mesh-delivery-assigner"
],
"env": {
"MESH_VIEW_CALLERS_ASKS": "mesh-delivery-teller,mesh-delivery-view",
"MESH_VIEW_CALLERS_ASSIGNMENTS": "mesh-grants,node-tools,mesh-delivery-indexer,mesh-delivery-builder,mesh-delivery-checker,mesh-delivery-view",
"MESH_VIEW_CALLERS_SEAT_HOLDERS": "node-tools,mesh-delivery-builder,mesh-delivery-view,mesh-delivery-teller,mesh-delivery-checker,mesh-delivery-indexer",
"MESH_VIEW_CALLERS_WANTS": "mesh-grants,mesh-delivery-view"
}
]
}
]
}
@@ -408,9 +408,8 @@ func main() {
pk.Start(context.Background())
// The build modules are no names (design 47 G A-82): the build seats on the seat list, each held by the module the catalog
// half's manifests say; the seat list and its two tools wired once by mesh-sdk (§204).
// Its callers name seats, never a module, resolved from the seat-holders view the catalog half's claimant serves (A-295, A-298).
gate := seatlist.NewPart("builder", []string{stdio.AnyPerson, stdio.CallerSeatPrefix + "node-tool-runner", stdio.CallerSeatPrefix + "mesh-healers"})
gate.Holders(branches.SeatHolders(context.Background()))
// Its tools are open to every caller, so the part resolves no caller's seat to its holder (design 47 H H-A-66).
gate := seatlist.NewPart("builder")
go func() {
<-stdio.Served()
gate.Follow(seatlist.StdioBus(), nil, func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-builder-tools] "+f+"\n", a...) })
@@ -132,6 +132,20 @@ func (c *catalogHalf) Changed(ctx context.Context) func(branch, module string, e
}
}
// picture is build.Builder.Picture: the source revision the view of branch holds (design 47 H H-A-155), false while the branch
// is not followed or its view holds none.
func (c *catalogHalf) picture(branch string) (int64, bool) {
cat, ok := c.branches.Catalog(branch)
if !ok {
return 0, false
}
half, ok := cat.View()
if !ok {
return 0, false
}
return half.Revision.Source, true
}
// namesOf are the package names an entry's artifacts carry, in one line.
func namesOf(e meshcatalog.CatalogEntry) string {
var names []string
@@ -33,8 +33,13 @@ type catalogHolder struct {
mu sync.Mutex
entries map[string]meshcatalog.CatalogEntry
revision int64
// source is the source revision each trunk revision is taken in from; 0 is 1.
source int64
}
// sourceLocked is the source revision of the revisions put now. The caller holds mu.
func (h *catalogHolder) sourceLocked() int64 { return max(h.source, 1) }
func newCatalogHolder(t *testing.T, ctx context.Context, js jetstream.JetStream, nc *nats.Conn) *catalogHolder {
t.Helper()
h := &catalogHolder{ctx: ctx, js: js, entries: map[string]meshcatalog.CatalogEntry{}}
@@ -84,7 +89,7 @@ func (h *catalogHolder) whole() meshcatalog.RevisionAnswer {
all = append(all, e)
}
at := time.Now()
return meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{Revision: h.revision, Kind: "trunk", Branch: "main", Entries: refs, Source: 1, At: &at}, Entries: all}
return meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{Revision: h.revision, Kind: "trunk", Branch: "main", Entries: refs, Source: h.sourceLocked(), At: &at}, Entries: all}
}
// put sets one module's entry in a new trunk revision of main and says catalog-revision.
@@ -100,7 +105,7 @@ func (h *catalogHolder) putAll(t *testing.T, es ...meshcatalog.CatalogEntry) {
h.entries[e.Module] = e
changed = append(changed, e.Module)
}
ev, _ := json.Marshal(meshcatalog.CatalogRevisionEvent{Branch: "main", Kind: "trunk", Revision: h.revision, Source: 1, Entries: int64(len(h.entries)), Changed: changed, V: 1})
ev, _ := json.Marshal(meshcatalog.CatalogRevisionEvent{Branch: "main", Kind: "trunk", Revision: h.revision, Source: h.sourceLocked(), Entries: int64(len(h.entries)), Changed: changed, V: 1})
h.mu.Unlock()
if _, err := h.js.Publish(h.ctx, meshcatalog.SubjectCatalogRevision("main"), ev); err != nil {
t.Fatal(err)
@@ -414,7 +414,7 @@ func (b *bed) manifestOf(t *testing.T, fixture string) map[string]any {
// entry is the catalog graph entry of a module as the holder answers it.
func (b *bed) entry(name, path, at, fp2, digest string, manifest map[string]any, toolchains map[string]builds.ToolchainUsed, src uint64) meshcatalog.CatalogEntry {
return meshcatalog.CatalogEntry{Module: name, Repository: "novox/mesh-catalog", Commit: at, Fp: fp2, Path: path, ManifestDigest: digest, Manifest: manifest,
Inputs: &meshcatalog.EntryInputs{Toolchains: build.CatalogToolchains(toolchains), Src: int64(src)}}
Inputs: &meshcatalog.EntryInputs{Toolchains: build.CatalogToolchains(toolchains)}}
}
// archive writes modules.<name> as the real indexer does for a module of an archive only: its fingerprint names no
@@ -522,9 +522,9 @@ 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).
func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
b := startBed(t)
// DLV-B10 (design 51, round 2): the builder's versions, findings and the floor's three sources are on the bus; the seat
// answers 0.1.4, so netcheck's bundles are numbered from 0.1.5. Two merges close together, the first replaced before
// its claim: the second is numbered at once, and the first never.
// The builder's versions, findings and the floor's three sources 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,
// G §348, §369): the reservation is the one place a version is numbered.
reg := b.registry(t, "n1", "0.1.4")
const netcheck = "catalogue-a67f0196-netcheck.module.json"
first := "src2:" + strings.Repeat("1", 64)
@@ -534,8 +534,8 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
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) != 1 || es[0].Version != "0.1.5" || es[0].Fingerprint != fp || es[0].State != versions.Numbered || es[0].Digest != digestOf(a) {
t.Errorf("versions of netcheck/%s = %+v, want the second merge numbered 0.1.5 at once with its digest, the first never", a, es)
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 {
@@ -565,13 +565,13 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
}
// 1955/L7 (ADR 0571 §1): the build's start and end are in the module log build-log under the module's key, read as a
// reader with the log's read reads them, the end naming the manifest and what was made.
// DLV-B10: between them the build log holds the build's narrations (build.said), each version numbered, and why.
// H-A-159: no version is numbered of the builder's own, so the build log holds no narration of one (build.said).
var ended []builds.BuildLogEntry
for _, e := range b.logged(t, "netcheck") {
if e.Event != builds.BuildSaidEvent {
ended = append(ended, e)
} else if e.Why != versions.SaidNumbered || !strings.Contains(e.Line, "numbered 0.1.5") || e.FP != fp {
t.Errorf("said = %+v, want netcheck's versions numbered", e)
} else if e.Why == versions.SaidNumbered || e.Why == versions.SaidKept {
t.Errorf("said = %+v, want no version of the builder's own numbered (H-A-159)", e)
}
}
if len(ended) != 2 || ended[0].Event != builds.BuildStartedEvent || ended[1].Event != builds.BuildEndedEvent ||
@@ -596,7 +596,7 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
}
}
// Design 32, design 47 G §348: a package's name the catalog half's entry of the module gives later reaches the builder by the
// branch follower's view (never the indexer's state), and looks at the module again; the done bundles are kept, not numbered twice.
// branch follower's view (never the indexer's state), and looks at the module again.
named := b.entry("netcheck", "modules/netcheck", commit, fp, digest, nil, bothToolchains, 0)
named.Manifest = b.manifestOf(t, "catalogue-a67f0196-netcheck.module.json")
named.Artifacts = []meshcatalog.Artifact{{Ref: "netcheck:lib", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "netcheck"}}}
@@ -606,11 +606,12 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
}
for _, a := range []string{"tools-go", "tools-typescript"} {
reg.published(t, "netcheck/"+a, "0.1.5", digestOf(a))
// 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)
}
reg.awaitOf(t, "netcheck/tools-go", func(es []versions.Entry) bool { return len(es) == 1 && es[0].State == versions.Published })
// A numbered version a holder will refuse below, written to the state as the builder numbers one.
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 {
@@ -643,7 +644,7 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
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
// fingerprint built again keeps its number, said with why, and its done build clears the finding.
// fingerprint built again clears it with its done build, numbering nothing of the builder's own (H-A-159).
release := make(chan struct{})
b.fake.hang.Store(&release)
third := "src2:" + strings.Repeat("4", 64)
@@ -666,12 +667,6 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
close(release)
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.awaitSaid(t, "kept: fingerprint "+third+" is numbered under it")
if !slices.ContainsFunc(b.logged(t, "netcheck"), func(e builds.BuildLogEntry) bool {
return e.Event == builds.BuildSaidEvent && e.Why == versions.SaidKept && e.FP == third && strings.Contains(e.Line, "kept: fingerprint "+third)
}) {
t.Errorf("the build log of netcheck says no version kept at %s", third)
}
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
// removal turns the entry removed with its reason, a refusal refused with the holder's reason and the bytes it refused.
@@ -35,6 +35,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
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/meshbuilds"
"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-sdk/go/operatorask"
"git.novox.be/novox/mesh-sdk/go/process"
@@ -121,9 +122,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// The part's own buckets are `<module>_<state>` of the credential's module (design 47 G A-296).
own := ownBucketsOf(cred.Module)
seatGate := newSeatGate()
// The part's one holder function (A-298): the seat list's callers and the views found by their seat (§717) read it.
// The part's one holder function (A-298): the views found by their seat (§717) read it; the seat list names no callers
// (design 47 H H-A-66).
holders := branches.SeatHolders(ctx)
seatGate.Holders(holders)
seats := buildrun.NewBuildSeats(seatGate.definitions, versions.HolderOf(branches))
bound := defaultStepBound
if v := strings.TrimSpace(getenv("MESH_BUILDER_STEP_BOUND")); v != "" {
@@ -156,9 +157,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
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 seat verb held, novox/hq issue 1937) before it leaves the key done, on its calls connection.
// The builder numbers each trunk build at its claim (novox/hq design 51 *The versions*): its state versions, bound once
// the bus holds it; the floor's three sources asked as its own account.
versionsKV := process.AwaitBucket(ctx, js, conn, own.versions, "no trunk build is numbered: each is built unnumbered and published by its digest", logger.Printf)
// 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}
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
@@ -205,13 +206,28 @@ 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,
bound: meshconditionsclient.CallUnansweredAfter, now: time.Now, logf: logger.Printf}
b.Left, b.Ended = unput.left, unput.ended
b.Numbers = build.VersionNumbers{N: numberer}
// 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
// is numbered in the state versions, waits on a floor or arms a publish-unanswered bound of it; the reservation is the one
// 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
// bound is its setting toolchain-wait-minutes.
waitBound, err := toolchainWaitOf(getenv("MESH_BUILDER_TOOLCHAIN_WAIT_FILE"))
if err != nil {
return err
}
// A build step ask waits for the builder's picture of its branch to hold its source revision (design 47 H H-A-155); its
// bound is its setting revision-wait-minutes (H-A-156).
revisionWait, err := numberFile(getenv("MESH_BUILDER_REVISION_WAIT_FILE"), int(build.DefaultRevisionWait/time.Minute))
if err != nil {
return err
}
b.RevisionWait = time.Duration(revisionWait) * time.Minute
// A step ask naming a package with no pin waits for its release (H-A-165); its bound is package-wait-minutes.
packageWait, err := numberFile(getenv("MESH_BUILDER_PACKAGE_WAIT_FILE"), int(build.DefaultPackageWait/time.Minute))
if err != nil {
return err
}
b.PackageWait = time.Duration(packageWait) * time.Minute
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 {
return emitEvent(context.WithoutCancel(ctx), js, cred, event, id, body)
@@ -226,6 +242,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return emitSeatEvent(context.WithoutCancel(ctx), js, cred, meshbuilds.SubjectPackagePublished, "package-published-"+p.Module+"-"+p.Version+"-"+p.Artifact, p)
}
b.Reserved = reserved
// A release heard, or the newest the builder's record keeps, pins a package an entry names with none (H-A-165).
reserved.heardReleased = b.VersionReleased
b.NewestReleased = reserved.r.NewestReleased
// The last versions-filled the stream keeps is read at the start (design 47 G §369, §372): a restart does not lose it.
reserved.readFilled(ctx, lastKeptOf(js, cred, logger.Printf), sleeps)
// A state bound later numbers the builds looked at without it.
@@ -399,7 +418,7 @@ 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
// 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.
// The same consumer carries what wakes a floor (design 51 *The floor*): the indexer's manifest-accepted and the
// 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.
@@ -416,7 +435,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}
heardGone(ctx, b, m, logger.Printf)
}
// The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, manifest-accepted 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
// catalog half's catalog-revision and registration-changed and the gate's source-moved are the views reader's (a message has
// one taker, so no pattern here covers them).
@@ -450,6 +469,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// fingerprint no branch carries is closed (issue 1660) once the first view of every followed branch is in (never at the start:
// a holder of the seat that is down holds no other part of it).
half.b = b
b.Picture = half.picture
branches.Held = func(string, meshcatalog.CatalogRevision) { b.PictureHeld() } // a revision held wakes a step ask's wait (H-A-162)
half.ready = func() {
if err := b.Sweep(ctx, half.pictured()...); err != nil {
errs <- err
@@ -9,7 +9,7 @@ const namedTreePrefix = "named:"
// 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
// seat's events and, of the seat mesh-catalog, manifest-accepted, version-released and versions-filled. The seat mesh-catalog's
// 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
// 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.
var seatEventPatterns = func() []string {
@@ -18,8 +18,9 @@ var seatEventPatterns = func() []string {
"mesh-artifact-sweep", "mesh-conditions", "node-engine", "node-build-go", "node-build-image", "node-build-node"} {
out = append(out, "mesh.seat."+seat+".event.>")
}
for _, event := range []string{meshcatalog.EventManifestAccepted, meshcatalog.EventVersionReleased, meshcatalog.EventVersionsFilled} {
for _, event := range []string{meshcatalog.EventVersionReleased, meshcatalog.EventVersionsFilled} {
out = append(out, "mesh.seat."+meshcatalog.Seat+".event."+event, "mesh.seat."+meshcatalog.Seat+".event."+event+".>")
}
return out
// And the indexer's take-in.taken, which wakes the floor (design 47 H H-A-116).
return append(out, takenInSubject)
}()
@@ -32,9 +32,13 @@ func TestTheNamesAreTheManifests(t *testing.T) {
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 catalog half (design 47 G §348, §614) is followed through the seat, and no state of the indexer is; the indexer's
// event take-in.taken wakes the floor (design 47 H 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 {
if strings.HasPrefix(c, "mesh-delivery-indexer.") {
if strings.HasPrefix(c, "mesh-delivery-indexer.") && c != "mesh-delivery-indexer.take-in.taken" {
t.Errorf("the builder follows %s, an indexer state, its manifest consumes it", c)
}
}
@@ -257,9 +257,9 @@ func aFloorsWakeIsHeard(t *testing.T) {
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: manifestAcceptedSubject}
if !f.heard(context.Background(), accepted) || !accepted.acked || !strings.Contains(logs.String(), "the floor of m/lib is asked again: manifest-accepted") {
t.Fatalf("manifest-accepted: acked %v, log %q", accepted.acked, logs.String())
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"}}`)}
@@ -299,8 +299,8 @@ func aFloorsWakeIsHeard(t *testing.T) {
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())
}
if h.heard(context.Background(), &wakeMsg{subject: manifestAcceptedSubject}) {
t.Fatal("manifest-accepted was taken as a seat's outcome")
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.
for _, n := range []uint64{4, EventDeliveries} {
@@ -44,12 +44,15 @@ type reservations struct {
// built asks a done build's publish (design 47 G A-457a), released ends its item; nil are none.
built func(ctx context.Context, module, version string) error
released func(ctx context.Context, module, version string)
filled atomic.Bool
bounds func() jetstream.KeyValue
found *findings
bound time.Duration
wake func(context.Context)
logf func(string, ...any)
// heardReleased is told each version-released taken in (design 47 H H-A-165): a step ask waiting for a package of the
// module wakes. Nil tells nobody.
heardReleased func(module, version string)
filled atomic.Bool
bounds func() jetstream.KeyValue
found *findings
bound time.Duration
wake func(context.Context)
logf func(string, ...any)
// call asks a seat's verb: the git seat's tag (design 47 G §370).
call toolCaller
// say says package-published on the seat mesh-builds; nil says none.
@@ -252,6 +255,9 @@ func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
if rv.released != nil {
rv.released(ctx, ev.Module, ev.Version)
}
if rv.heardReleased != nil {
rv.heardReleased(ev.Module, ev.Version)
}
rv.found.clear(ctx, versions.VersionUnreleased, meshconditionsclient.ScopeModule, ev.Module)
default:
return false
@@ -134,10 +134,15 @@ func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
if err != nil || !strings.Contains(got.Summary, "m:b unpublished") || strings.Contains(got.Summary, "m:a unpublished") || !strings.Contains(got.Summary, "1.4.3") {
t.Fatalf("finding = %+v (%v), want version-unreleased naming m:b of 1.4.3", got, err)
}
var heardReleases []string // H-A-165: a release heard wakes a step ask waiting for a package of the module
rv.heardReleased = func(m, v string) { heardReleases = append(heardReleases, m+" "+v) }
released := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"m","version":"1.4.3","source":1,"artifacts":[]}`)}
if !rv.heard(ctx, released) || !released.acked {
t.Fatalf("version-released was not taken in (acked %v)", released.acked)
}
if strings.Join(heardReleases, ", ") != "m 1.4.3" {
t.Errorf("the release heard was told %v, want m 1.4.3 (H-A-165)", heardReleases)
}
if strings.Join(items, ", ") != "asked m 1.4.3, ended m 1.4.3" {
t.Errorf("publish items %v, want the build's end to ask the publish and the release to end it", items)
}
@@ -3,20 +3,17 @@ package main
import (
"git.novox.be/novox/mesh-sdk/go/seatdef"
"git.novox.be/novox/mesh-sdk/go/seatlist"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The builder reads the seat list as every part does, through mesh-sdk's one wiring (go/seatlist.Part; design 47 G §204): its
// definitions name the build seats (the seats whose acting rule is the step build), its tools `builder_seat_list` and
// `builder_seat_list_again`. A call through the mesh MCP server is proved only as its machine's tool runner (issue 627). The
// list names seats, never a module, resolved by the holder function meshcatalogclient's SeatHolders answers (A-295, A-298).
var seatListAgainCallers = []string{stdio.AnyPerson, stdio.CallerSeatPrefix + "node-tool-runner", stdio.CallerSeatPrefix + "mesh-healers"}
// `builder_seat_list_again`, open to every caller (design 47 H H-A-66). The list names seats, never a module, resolved by the
// holder function meshcatalogclient's SeatHolders answers (A-295, A-298).
// seatGate is the builder's wiring of the seat list.
type seatGate struct{ *seatlist.Part }
func newSeatGate() *seatGate { return &seatGate{seatlist.NewPart("builder", seatListAgainCallers)} }
func newSeatGate() *seatGate { return &seatGate{seatlist.NewPart("builder")} }
// definitions are the seat definitions the list holds, none before it is read.
func (g *seatGate) definitions() map[string]seatdef.Definition {
@@ -4,6 +4,7 @@ package main
import (
"encoding/json"
"strings"
"testing"
"time"
@@ -49,4 +50,29 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) {
case <-time.After(20 * time.Second):
t.Fatal("no step-ended within 20 s")
}
// H-A-155: an ask naming a source revision the builder's picture of main does not hold yet waits for it, said in the
// journal, and is answered once a revision taken in from it arrives.
run.Pipeline, run.Revision, run.Source = "main.2.netcheck", 2, 2
data, _ = json.Marshal(run)
msg = nats.NewMsg(meshbuilds.AcceptSubjectStep)
msg.Data = data
msg.Header.Set("x-event-id", "ask-2")
if err := sub.PublishMsg(msg); err != nil {
t.Fatal(err)
}
b.awaitSaid(t, "main.2.netcheck: revision 2 of main not in the builder's picture yet")
b.catalog.mu.Lock()
b.catalog.source = 2
b.catalog.mu.Unlock()
// Revision 2, taken in from source 2, moves another module: netcheck's entry is the one the picture holds already.
b.moduleFP(t, "ca-trust", "catalogue-a67f0196-ca-trust.module.json", "modules/ca-trust", nil, commit, "src2:"+strings.Repeat("4", 64), 0)
select {
case m := <-ended:
var end meshbuilds.StepEnded
if err := json.Unmarshal(m.Data, &end); err != nil || end.ID != "ask-2" || end.Outcome != meshbuilds.StepEndedOutcomePassed {
t.Fatalf("step-ended = %+v, %v; want the ask ask-2 passed once the picture held source revision 2", end, err)
}
case <-time.After(20 * time.Second):
t.Fatal("no step-ended for ask-2 within 20 s")
}
}
@@ -13,7 +13,6 @@ import (
"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/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-builder/internal/build"
@@ -189,7 +188,8 @@ func emitSeatEvent(ctx context.Context, js jetstream.JetStream, cred process.Acc
// The events on the builder's consumer of EVENTS that wake a floor (design 51 *The floor*, DLV-B3b).
var (
manifestAcceptedSubject = meshcatalog.SubjectManifestAccepted
// 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
)
@@ -204,9 +204,9 @@ type floorWake struct {
// 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 manifestAcceptedSubject:
case takenInSubject:
f.ack(m)
f.wake(ctx, versions.WakeAccepted, "", "")
f.wake(ctx, versions.WakeTakenIn, "", "")
case conditionClearedSubject:
f.ack(m)
var e meshconditions.ConditionEvent

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