From d4650bb8102a414802c4e3eaf44159df067d7390 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Sat, 5 Dec 2026 00:30:17 -0800 Subject: [PATCH 1/2] Expose orchestrator Ethereum addresses in discovery Publish the Ethereum address as `orchestrator` in discovery responses. Forward it through standalone discovery and the signer. Update the discovery schema, HTTP examples, and tests. --- discovery/schema_test.go | 3 +++ discovery/server.go | 15 +++++++------ discovery/server_test.go | 23 +++++++++----------- discovery/shared/inventory.go | 25 +++++++++++++++------- discovery/shared/inventory_test.go | 29 ++++++++++++++++++++++++- docs/discovery.schema.json | 7 +++++- docs/http-api.md | 34 ++++++++++++++++++++++-------- orchestrator/app_test.go | 3 ++- orchestrator/discovery_test.go | 1 + orchestrator/http.go | 1 + orchestrator/payment_test.go | 3 +++ orchestrator/registry.go | 9 +++++--- signer/discovery_test.go | 5 ++++- signer/service.go | 8 +++---- 14 files changed, 119 insertions(+), 47 deletions(-) diff --git a/discovery/schema_test.go b/discovery/schema_test.go index 021be6a..9712a58 100644 --- a/discovery/schema_test.go +++ b/discovery/schema_test.go @@ -46,6 +46,9 @@ func TestDiscoverySchema(t *testing.T) { }{ {"empty", `[]`, true}, {"empty runners", envelope(""), true}, + {"Ethereum address", `[{"address":"https://orch.example","orchestrator":"0x111111111111111111111111111111111111AbCd","runners":[]}]`, true}, + {"short Ethereum address", `[{"address":"https://orch.example","orchestrator":"0x1111","runners":[]}]`, false}, + {"non-string Ethereum address", `[{"address":"https://orch.example","orchestrator":1234,"runners":[]}]`, false}, {"metadata", metadata, true}, {"metadata with empty runners", `[{"nodes":[],"runners":[]}]`, true}, {"minimal runner", envelope(runner), true}, diff --git a/discovery/server.go b/discovery/server.go index 89e3e44..6255916 100644 --- a/discovery/server.go +++ b/discovery/server.go @@ -165,7 +165,7 @@ func (d *Server) Run(ctx context.Context) { d.collector.Run(ctx, d.interval) } -func (s *Server) discoveryResponse() []map[string]any { +func (s *Server) discoveryResponse() []discoveryResponseEntry { nodes := []discoveryNode{} entries := []discoveryEntry{} for _, snapshot := range s.collector.Snapshots() { @@ -176,15 +176,14 @@ func (s *Server) discoveryResponse() []map[string]any { entries = append(entries, snapshot.Entries...) } } - result := []map[string]any{} + result := []discoveryResponseEntry{} if len(nodes) > 0 { - result = append(result, map[string]any{"nodes": nodes}) + result = append(result, discoveryResponseEntry{Nodes: nodes}) } for _, entry := range discovery.Merge(entries) { - if len(entry.Runners) == 0 { - continue + if len(entry.Runners) > 0 { + result = append(result, discoveryResponseEntry{discoveryEntry: &entry}) } - result = append(result, map[string]any{"address": entry.Address, "runners": entry.Runners}) } return result } @@ -277,3 +276,7 @@ func (r discoveryRunner) DiscoveryIdentity() (string, string, string) { } type discoveryEntry = discovery.Entry[discoveryRunner] +type discoveryResponseEntry struct { + *discoveryEntry + Nodes []discoveryNode `json:"nodes,omitempty"` +} diff --git a/discovery/server_test.go b/discovery/server_test.go index 6268931..8242c51 100644 --- a/discovery/server_test.go +++ b/discovery/server_test.go @@ -59,7 +59,7 @@ func TestDiscoverySourcePolicy(t *testing.T) { s.collector.MaxFailures = 1 s.collector.Refresh(t.Context(), false) require.Len(t, s.discoveryResponse(), 3) - require.Equal(t, upstream.URL+"/deployment", s.discoveryResponse()[0]["nodes"].([]discoveryNode)[0].URL) + require.Equal(t, upstream.URL+"/deployment", s.discoveryResponse()[0].Nodes[0].URL) s.collector.Refresh(t.Context(), false) require.Empty(t, s.discoveryResponse()) require.Equal(t, int32(2), calls.Load(), "neither redirects nor advertised nodes may be followed") @@ -93,17 +93,16 @@ func TestDiscoveryWorkerSchedulingAndCancellation(t *testing.T) { go func() { defer close(done); s.Run(ctx) }() synctest.Wait() result := s.discoveryResponse() - metadataEntries := 0 + wantEntries := 0 if flags.nodes { - metadataEntries = 1 - require.Contains(t, result[0], "nodes") - require.NotContains(t, result[0], "address") + wantEntries++ + require.Len(t, result[0].Nodes, 1) + require.Nil(t, result[0].discoveryEntry) } if flags.runners { - require.Len(t, result, 2+metadataEntries) - } else { - require.Len(t, result, metadataEntries) + wantEntries += 2 } + require.Len(t, result, wantEntries) if !flags.nodes && !flags.runners { <-done require.Zero(t, calls.Load()) @@ -112,9 +111,6 @@ func TestDiscoveryWorkerSchedulingAndCancellation(t *testing.T) { require.Equal(t, int32(1), calls.Load()) queried := snapshot().QueriedAt require.False(t, queried.IsZero()) - if flags.nodes { - require.Len(t, s.discoveryResponse()[0]["nodes"], 1) - } time.Sleep(5 * time.Minute) synctest.Wait() require.Equal(t, int32(2), calls.Load()) @@ -169,10 +165,10 @@ func TestDiscoveryBoundedConcurrencyAndPartialResults(t *testing.T) { close(slow) synctest.Wait() require.NotEmpty(t, partial) - require.Len(t, partial[0]["nodes"], 11, "completed sources are visible while another source stalls") + require.Len(t, partial[0].Nodes, 11, "completed sources are visible while another source stalls") require.Equal(t, int32(12), calls.Load()) require.LessOrEqual(t, maxActive.Load(), int32(5)) - require.Len(t, s.discoveryResponse()[0]["nodes"], 12) + require.Len(t, s.discoveryResponse()[0].Nodes, 12) }) } @@ -253,6 +249,7 @@ func TestDiscoveryPreservesWholeRecords(t *testing.T) { require.Len(t, nodes, 3) require.Equal(t, upstream.URL+"/old", nodes[0].URL) require.Equal(t, `"https://orch.example"`, string(result[1]["address"])) + require.NotContains(t, result[1], "orchestrator") // Compare raw JSON to retain unknown fields and exact numeric tokens. require.Equal(t, "["+record+"]", string(result[1]["runners"])) } diff --git a/discovery/shared/inventory.go b/discovery/shared/inventory.go index b420ec8..a7766c1 100644 --- a/discovery/shared/inventory.go +++ b/discovery/shared/inventory.go @@ -8,6 +8,7 @@ import ( "time" "github.com/livepeer/node/destination" + "github.com/livepeer/node/eth" ) const MaxBody = 3 << 20 @@ -19,8 +20,9 @@ type Runner interface { } type Entry[R Runner] struct { - Address string `json:"address"` - Runners []R `json:"runners"` + Address string `json:"address"` + Orchestrator string `json:"orchestrator,omitempty"` + Runners []R `json:"runners"` } // ValidateURL checks discovery base URLs, retaining deployment paths. @@ -43,9 +45,10 @@ func Read(body io.Reader) ([]byte, error) { // Empty inventories succeed; advertised runners with no valid candidates fail. func Decode[R Runner](data []byte, now time.Time) ([]Entry[R], error) { var wire []struct { - Address string `json:"address"` - Runners []json.RawMessage `json:"runners"` - Nodes json.RawMessage `json:"nodes"` + Address string `json:"address"` + Orchestrator json.RawMessage `json:"orchestrator"` + Runners []json.RawMessage `json:"runners"` + Nodes json.RawMessage `json:"nodes"` } if err := json.Unmarshal(data, &wire); err != nil || wire == nil { return nil, errors.New("discovery response must be an array of entries") @@ -62,11 +65,14 @@ func Decode[R Runner](data []byte, now time.Time) ([]Entry[R], error) { continue } } - address, err := url.Parse(entry.Address) - if err != nil || ValidateURL(address) != nil { + if address, err := url.Parse(entry.Address); err != nil || ValidateURL(address) != nil { continue } - out := Entry[R]{Address: entry.Address, Runners: make([]R, 0, len(entry.Runners))} + var recipient, orchestrator string + if entry.Orchestrator != nil && json.Unmarshal(entry.Orchestrator, &recipient) == nil && eth.ValidAddress(recipient) { + orchestrator = recipient + } + out := Entry[R]{Address: entry.Address, Orchestrator: orchestrator, Runners: make([]R, 0, len(entry.Runners))} for _, raw := range entry.Runners { var runner R if json.Unmarshal(raw, &runner) != nil { @@ -121,6 +127,9 @@ func Merge[R Runner](entries []Entry[R]) []Entry[R] { groups[entry.Address] = group result = append(result, Entry[R]{Address: entry.Address, Runners: []R{}}) } + if result[group].Orchestrator == "" { + result[group].Orchestrator = entry.Orchestrator + } for j, runner := range entry.Runners { endpoint, _, _ := runner.DiscoveryIdentity() win := winners[endpoint] diff --git a/discovery/shared/inventory_test.go b/discovery/shared/inventory_test.go index 8d63f67..8dc8b7b 100644 --- a/discovery/shared/inventory_test.go +++ b/discovery/shared/inventory_test.go @@ -66,15 +66,42 @@ func TestDecodeValidation(t *testing.T) { require.Error(t, err) } +func TestDecodeOrchestrator(t *testing.T) { + const recipient = "0x1111111111111111111111111111111111111111" + now := time.Date(2026, 10, 22, 18, 0, 0, 0, time.UTC) + for _, test := range []struct{ name, value, want string }{ + {"valid address", `"` + recipient + `"`, recipient}, + {"short address", `"0x1111"`, ""}, + {"non-string address", `1234`, ""}, + } { + t.Run(test.name, func(t *testing.T) { + body := fmt.Sprintf(`[{"address":"https://orch.example","orchestrator":%s,"runners":[%s]}]`, test.value, candidate(now.Format(time.RFC3339Nano))) + entries, err := Decode[record]([]byte(body), now) + require.NoError(t, err) + require.Len(t, entries, 1) + require.Len(t, entries[0].Runners, 1) + require.Equal(t, test.want, entries[0].Orchestrator) + }) + } +} + func TestMergePreservesFreshestWholeRecord(t *testing.T) { old := record{"https://r.example", "old", "2026-01-01T00:00:00Z", 4} newest := record{old.URL, "new", "2026-01-01T02:00:00.123+01:00", 1} tie := newest tie.App = "tie" - entries := []Entry[record]{{"https://a.example", []record{old}}, {"https://b.example", []record{newest}}, {"https://a.example", []record{tie, {"https://other.example", "other", old.Observed, 2}}}} + const recipient = "0x1111111111111111111111111111111111111111" + entries := []Entry[record]{ + {Address: "https://a.example", Runners: []record{old}}, + {Address: "https://b.example", Runners: []record{newest}}, + {Address: "https://a.example", Orchestrator: recipient, Runners: []record{tie, {"https://other.example", "other", old.Observed, 2}}}, + {Address: "https://a.example", Orchestrator: "0x2222222222222222222222222222222222222222"}, + } merged := Merge(entries) require.Len(t, merged, 2) require.Equal(t, "https://a.example", merged[0].Address) + require.Equal(t, recipient, merged[0].Orchestrator) + require.Empty(t, merged[1].Orchestrator) require.Equal(t, "https://other.example", merged[0].Runners[0].URL) require.Equal(t, []record{newest}, merged[1].Runners) // A second forwarding step preserves the original text and ownership. diff --git a/docs/discovery.schema.json b/docs/discovery.schema.json index f6ba370..8dca673 100644 --- a/docs/discovery.schema.json +++ b/docs/discovery.schema.json @@ -56,7 +56,12 @@ "properties": { "address": { "$ref": "#/$defs/baseURL", - "description": "The owning orchestrator's HTTP(S) base URL, including any deployment path; not an Ethereum address." + "description": "The owning orchestrator's public HTTP(S) base URL, including any deployment path." + }, + "orchestrator": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{40}$", + "description": "The Ethereum address used as TicketParams.Recipient in payment challenges. Omitted off-chain and when missing from the source inventory." }, "runners": { "type": "array", diff --git a/docs/http-api.md b/docs/http-api.md index 1e7657f..671e169 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -56,21 +56,22 @@ Dynamic runners are marked as ready in the heartbeat after registration. The response body follows the [discovery JSON Schema](discovery.schema.json). -`GET /discovery` returns available local runners at an orchestrator, or cached -runners grouped by owning orchestrator at standalone discovery. In this -live-runner format, `address` is the orchestrator's HTTP(S) base URL, such as -`https://orch.example.com:8935`; it is distinct from the orchestrator's Ethereum -wallet address. Standalone discovery prepends an optional `nodes` metadata entry -with no `address`: +`GET /discovery` lists local runners on an orchestrator. Standalone discovery +lists cached runners grouped by orchestrator. Each group includes the +orchestrator's public HTTP(S) base URL in `address` and its Ethereum address in +`orchestrator`. Standalone discovery may prepend an entry containing only +`nodes` metadata. ```json [ {"nodes": [ {"url": "https://orch.example.com:8935", "queried_at": "2026-10-22T18:05:00Z"} ]}, - {"address": "https://orch.example.com:8935", "runners": [ - {"url": "https://orch.example.com:8935/apps/a1/app", "app": "example", "observed_at": "2026-10-22T18:05:00Z"} - ]} + {"address": "https://orch.example.com:8935", + "orchestrator": "0x1111111111111111111111111111111111111111", + "runners": [ + {"url": "https://orch.example.com:8935/apps/a1/app", "app": "example", "observed_at": "2026-10-22T18:05:00Z"} + ]} ] ``` @@ -115,6 +116,21 @@ poll time of the cached source in UTC. At least one usable cached inventory yiel HTTP 200 (possibly `[]`); none yields 503. Cached results can remain available while a source is unreachable. +Runner details are abbreviated in this example. + +```json +[ + { + "address": "https://orch.example.com:8935", + "orchestrator": "0x1111111111111111111111111111111111111111", + "runners": [ + {"url": "https://orch.example.com:8935/apps/a1/app", "app": "example", "observed_at": "2026-10-22T18:05:00Z"} + ], + "last_seen": "2026-10-22T18:05:01Z" + } +] +``` + Grants restrict outbound connections, not returned URLs. See [signer discovery configuration](signer.md#configure-discovery). diff --git a/orchestrator/app_test.go b/orchestrator/app_test.go index 48114fb..0a926a6 100644 --- a/orchestrator/app_test.go +++ b/orchestrator/app_test.go @@ -182,7 +182,6 @@ func TestPaidHTTPStartup(t *testing.T) { defer store.Close() require.NoError(t, store.StoreWinningTicket(&pm.SignedTicket{Ticket: &pm.Ticket{PayerAddress: recipient, Recipient: recipient, FaceValue: big.NewInt(1000), WinProb: big.NewInt(100), TicketNonce: 1, RecipientRandHash: crypto.Keccak256Hash([]byte("failed ticket")), CreationRound: 1, CreationRoundBlockHash: rpc.State().RoundHash, ParamsExpirationBlock: big.NewInt(0)}, Sig: make([]byte, 65), RecipientRand: big.NewInt(1)})) } - releaseDependencies() response, err = client.Get(address + "/external/discovery") require.NoError(t, err) defer response.Body.Close() @@ -190,6 +189,8 @@ func TestPaidHTTPStartup(t *testing.T) { require.NoError(t, json.NewDecoder(response.Body).Decode(&entries)) require.Len(t, entries, 1) require.Equal(t, p.ServiceURL.String(), entries[0].Address) + require.Equal(t, recipient.Hex(), entries[0].Orchestrator) + releaseDependencies() payer := paymentTestKey(t) request, err := http.NewRequest(http.MethodPost, address+"/external/apps/r/session", nil) require.NoError(t, err) diff --git a/orchestrator/discovery_test.go b/orchestrator/discovery_test.go index 9b96812..5b18cac 100644 --- a/orchestrator/discovery_test.go +++ b/orchestrator/discovery_test.go @@ -57,6 +57,7 @@ func TestDiscoveryLocalInventory(t *testing.T) { require.NotContains(t, string(data), `"nodes"`) require.NotContains(t, string(data), `"app_id"`) require.NotContains(t, string(data), `"runner_id"`) + require.NotContains(t, string(data), `"orchestrator"`) var entries []discoveryEntry require.NoError(t, json.Unmarshal(data, &entries)) require.Len(t, entries, 1) diff --git a/orchestrator/http.go b/orchestrator/http.go index c406f65..d2e95db 100644 --- a/orchestrator/http.go +++ b/orchestrator/http.go @@ -238,6 +238,7 @@ func headerExcluded(name string, patterns []string) bool { return false } +// SetPayment configures the payment engine before the server starts serving. func (s *Server) SetPayment(engine *PaymentEngine) { s.payment = engine if engine != nil { diff --git a/orchestrator/payment_test.go b/orchestrator/payment_test.go index 4e93134..b382006 100644 --- a/orchestrator/payment_test.go +++ b/orchestrator/payment_test.go @@ -80,6 +80,9 @@ func TestPaidFixedSessionWithRemoteSigner(t *testing.T) { server := NewServer(registry, policy, policy, slog.New(slog.NewTextHandler(io.Discard, nil))) defer server.Close() server.SetPayment(engine) + inventory := registry.Discovery() + require.Len(t, inventory, 1) + require.Equal(t, recipient.Address().Hex(), inventory[0].Orchestrator) signerService, err := signer.NewService(payer) require.NoError(t, err) defer signerService.Close() diff --git a/orchestrator/registry.go b/orchestrator/registry.go index 966475f..df6fcca 100644 --- a/orchestrator/registry.go +++ b/orchestrator/registry.go @@ -625,7 +625,10 @@ type discoveryEntry = discovery.Entry[discoveryRunner] func (r *Registry) Discovery() []discoveryEntry { r.mu.Lock() defer r.mu.Unlock() - result := []discoveryRunner{} + entry := discoveryEntry{Address: r.service, Runners: []discoveryRunner{}} + if r.server != nil && r.server.payment != nil { + entry.Orchestrator = r.server.payment.recipient.Hex() + } observed := time.Now().UTC().Format(time.RFC3339Nano) for _, id := range slices.Sorted(maps.Keys(r.apps)) { item := r.apps[id] @@ -633,9 +636,9 @@ func (r *Registry) Discovery() []discoveryEntry { continue } available := max(0, item.Capacity-len(item.Sessions)) - result = append(result, discoveryRunner{ObservedAt: observed, URL: r.discoveryURL(id, item), App: item.App, Version: item.Version, Metadata: item.Metadata, GPU: item.GPU, Mode: item.Mode, Capacity: item.Capacity, CapacityUsed: len(item.Sessions), CapacityAvailable: available, PriceInfo: item.PriceInfo}) + entry.Runners = append(entry.Runners, discoveryRunner{ObservedAt: observed, URL: r.discoveryURL(id, item), App: item.App, Version: item.Version, Metadata: item.Metadata, GPU: item.GPU, Mode: item.Mode, Capacity: item.Capacity, CapacityUsed: len(item.Sessions), CapacityAvailable: available, PriceInfo: item.PriceInfo}) } - return []discoveryEntry{{Address: r.service, Runners: result}} + return []discoveryEntry{entry} } // Admission depends on readiness; admitted sessions depend only on liveness. diff --git a/signer/discovery_test.go b/signer/discovery_test.go index 80650d6..e576b25 100644 --- a/signer/discovery_test.go +++ b/signer/discovery_test.go @@ -28,7 +28,8 @@ func discoveryResponse(s *Service, query string) *httptest.ResponseRecorder { } func TestSignerDiscovery(t *testing.T) { - const advertised = `[{"address":"http://localhost:9000","runners":[{"url":"http://localhost:9000/app","observed_at":"2026-01-01T00:00:00Z","app":"retained","version":"v1","metadata":"model-x","mode":"single-shot","gpu":{"id":"0","name":" H100 ","vram_mb":80000},"capacity":3,"capacity_used":1,"capacity_available":2,"price_info":{"price":10,"price_usd":0.1,"currency":"wei","unit":"fixed"}},{"url":"http://localhost:9000/cpu","observed_at":"2026-01-01T00:00:00Z","app":"cpu","mode":"single-shot","capacity":1,"price_info":{"price":1,"currency":"wei","unit":"fixed"}}]}]` + const recipient = "0x111111111111111111111111111111111111AbCd" + const advertised = `[{"address":"http://localhost:9000","orchestrator":"` + recipient + `","runners":[{"url":"http://localhost:9000/app","observed_at":"2026-01-01T00:00:00Z","app":"retained","version":"v1","metadata":"model-x","mode":"single-shot","gpu":{"id":"0","name":" H100 ","vram_mb":80000},"capacity":3,"capacity_used":1,"capacity_available":2,"price_info":{"price":10,"price_usd":0.1,"currency":"wei","unit":"fixed"}},{"url":"http://localhost:9000/cpu","observed_at":"2026-01-01T00:00:00Z","app":"cpu","mode":"single-shot","capacity":1,"price_info":{"price":1,"currency":"wei","unit":"fixed"}}]}]` const maxBytes = 3 << 20 bodies := map[string]string{ "empty": "[]", "good": advertised, "failed": "", "malformed": "not JSON", @@ -133,6 +134,7 @@ func TestSignerDiscovery(t *testing.T) { require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) require.Len(t, result, 1) require.Equal(t, expected[0].Address, result[0].Address) + require.Equal(t, recipient, result[0].Orchestrator) want := slices.DeleteFunc(slices.Clone(expected[0].Runners), func(r discoveredRunner) bool { return !slices.Contains(test.apps, r.App) }) require.Equal(t, want, result[0].Runners, "preserve advertised fields and URLs") }) @@ -225,6 +227,7 @@ func TestSignerDiscoveryFreshnessMerge(t *testing.T) { require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) require.Len(t, result, 1) require.Equal(t, "https://owner-new.example", result[0].Address) + require.NotContains(t, w.Body.String(), `"orchestrator"`) require.Len(t, result[0].Runners, 2) require.Equal(t, 1, result[0].Runners[0].Capacity) require.Equal(t, "2026-01-01T02:00:00.123+01:00", result[0].Runners[0].ObservedAt) diff --git a/signer/service.go b/signer/service.go index 49bf650..caf9bfc 100644 --- a/signer/service.go +++ b/signer/service.go @@ -246,9 +246,8 @@ func (r discoveredRunner) DiscoveryIdentity() (string, string, string) { } type discoveredOrchestrator struct { - Address string `json:"address"` - Runners []discoveredRunner `json:"runners"` - LastSeen time.Time `json:"last_seen"` + discovery.Entry[discoveredRunner] + LastSeen time.Time `json:"last_seen"` } func (s *Service) discover(w http.ResponseWriter, r *http.Request) { @@ -292,7 +291,8 @@ func (s *Service) discover(w http.ResponseWriter, r *http.Request) { filtered = append(filtered, runner) } if len(filtered) > 0 { - result = append(result, discoveredOrchestrator{Address: entry.Address, Runners: filtered, LastSeen: observations[entry.Address]}) + entry.Runners = filtered + result = append(result, discoveredOrchestrator{Entry: entry, LastSeen: observations[entry.Address]}) } } From 35dfb7ed60013cea82f8c853f15199c08756f309 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Sat, 5 Dec 2026 00:55:02 -0800 Subject: [PATCH 2/2] Select the discovery recipient from the newest retained runner --- discovery/shared/inventory.go | 10 ++++++---- discovery/shared/inventory_test.go | 30 +++++++++++++++++++++++++++++- docs/http-api.md | 3 +++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/discovery/shared/inventory.go b/discovery/shared/inventory.go index a7766c1..5568259 100644 --- a/discovery/shared/inventory.go +++ b/discovery/shared/inventory.go @@ -65,7 +65,8 @@ func Decode[R Runner](data []byte, now time.Time) ([]Entry[R], error) { continue } } - if address, err := url.Parse(entry.Address); err != nil || ValidateURL(address) != nil { + address, err := url.Parse(entry.Address) + if err != nil || ValidateURL(address) != nil { continue } var recipient, orchestrator string @@ -120,6 +121,7 @@ func Merge[R Runner](entries []Entry[R]) []Entry[R] { } result := make([]Entry[R], 0, len(entries)) groups := make(map[string]int) + latestObserved := make(map[int]time.Time) for i, entry := range entries { group, exists := groups[entry.Address] if !exists { @@ -127,13 +129,13 @@ func Merge[R Runner](entries []Entry[R]) []Entry[R] { groups[entry.Address] = group result = append(result, Entry[R]{Address: entry.Address, Runners: []R{}}) } - if result[group].Orchestrator == "" { - result[group].Orchestrator = entry.Orchestrator - } for j, runner := range entry.Runners { endpoint, _, _ := runner.DiscoveryIdentity() win := winners[endpoint] if win.entry == i && win.runner == j { + if len(result[group].Runners) == 0 || win.observed.After(latestObserved[group]) { + latestObserved[group], result[group].Orchestrator = win.observed, entry.Orchestrator + } result[group].Runners = append(result[group].Runners, runner) } } diff --git a/discovery/shared/inventory_test.go b/discovery/shared/inventory_test.go index 8dc8b7b..f6f9fca 100644 --- a/discovery/shared/inventory_test.go +++ b/discovery/shared/inventory_test.go @@ -95,15 +95,43 @@ func TestMergePreservesFreshestWholeRecord(t *testing.T) { {Address: "https://a.example", Runners: []record{old}}, {Address: "https://b.example", Runners: []record{newest}}, {Address: "https://a.example", Orchestrator: recipient, Runners: []record{tie, {"https://other.example", "other", old.Observed, 2}}}, - {Address: "https://a.example", Orchestrator: "0x2222222222222222222222222222222222222222"}, + {Address: "https://a.example", Orchestrator: "0x2222222222222222222222222222222222222222", Runners: []record{{"https://third.example", "third", old.Observed, 3}}}, } merged := Merge(entries) require.Len(t, merged, 2) require.Equal(t, "https://a.example", merged[0].Address) require.Equal(t, recipient, merged[0].Orchestrator) require.Empty(t, merged[1].Orchestrator) + require.Len(t, merged[0].Runners, 2) require.Equal(t, "https://other.example", merged[0].Runners[0].URL) require.Equal(t, []record{newest}, merged[1].Runners) // A second forwarding step preserves the original text and ownership. require.Equal(t, merged, Merge(merged)) } + +func TestMergeRecipientFollowsNewestRunner(t *testing.T) { + const address = "https://orch.example" + const oldRecipient = "0x1111111111111111111111111111111111111111" + const newRecipient = "0x2222222222222222222222222222222222222222" + old := record{"https://r.example", "test", "2026-01-01T00:00:00Z", 1} + fresh := record{old.URL, old.App, "2026-01-01T01:00:00Z", 1} + other := record{"https://other.example", old.App, old.Observed, 1} + for _, test := range []struct { + name, recipient string + oldRunners []record + }{ + {"recipient changes", newRecipient, []record{old}}, + {"new inventory omits recipient", "", []record{old, other}}, + {"older runner also wins", newRecipient, []record{old, other}}, + } { + t.Run(test.name, func(t *testing.T) { + merged := Merge([]Entry[record]{ + {Address: address, Orchestrator: oldRecipient, Runners: test.oldRunners}, + {Address: address, Orchestrator: test.recipient, Runners: []record{fresh}}, + }) + require.Len(t, merged, 1) + require.Contains(t, merged[0].Runners, fresh) + require.Equal(t, test.recipient, merged[0].Orchestrator) + }) + } +} diff --git a/docs/http-api.md b/docs/http-api.md index 671e169..29490fa 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -91,6 +91,9 @@ Collectors and signers skip missing/invalid timestamps and those over 30 seconds in the future. Empty inventories succeed; sources advertising runners with no valid records fail. Duplicate runner URLs use the newest record and its owning address; ties keep the first in source, entry, then runner order. +For each base URL, the entry with the newest retained runner observation +determines `orchestrator`. If that entry omits the field, the merged entry omits +it too. Equal timestamps keep source and entry order. ## Remote signer HTTP