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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions discovery/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
15 changes: 9 additions & 6 deletions discovery/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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
}
Expand Down Expand Up @@ -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"`
}
23 changes: 10 additions & 13 deletions discovery/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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())
Expand All @@ -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())
Expand Down Expand Up @@ -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)
})
}

Expand Down Expand Up @@ -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"]))
}
Expand Down
23 changes: 17 additions & 6 deletions discovery/shared/inventory.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/livepeer/node/destination"
"github.com/livepeer/node/eth"
)

const MaxBody = 3 << 20
Expand All @@ -20,8 +21,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.
Expand All @@ -44,9 +46,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")
Expand All @@ -67,7 +70,11 @@ func Decode[R Runner](data []byte, now time.Time) ([]Entry[R], error) {
if err != nil || ValidateURL(address) != nil {
continue
}
out := Entry[R]{Address: strings.TrimSuffix(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: strings.TrimSuffix(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 {
Expand Down Expand Up @@ -115,6 +122,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 {
Expand All @@ -126,6 +134,9 @@ func Merge[R Runner](entries []Entry[R]) []Entry[R] {
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)
}
}
Expand Down
57 changes: 56 additions & 1 deletion discovery/shared/inventory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,72 @@ 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", 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)
})
}
}
7 changes: 6 additions & 1 deletion docs/discovery.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
37 changes: 28 additions & 9 deletions docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
]}
]
```

Expand All @@ -90,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

Expand All @@ -115,6 +119,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).

Expand Down
3 changes: 2 additions & 1 deletion orchestrator/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,15 @@ 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()
var entries []discoveryEntry
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)
Expand Down
1 change: 1 addition & 0 deletions orchestrator/discovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions orchestrator/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions orchestrator/payment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions orchestrator/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -625,17 +625,20 @@ 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]
if !r.usable(item) || !r.priceAvailable(item) {
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.
Expand Down
Loading
Loading