From 5337378b93dacd2f28919fedc40c60e08ae75173 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Wed, 4 Nov 2026 19:04:35 -0800 Subject: [PATCH] Publish JSON Schema for discovery responses --- discovery/schema_test.go | 106 +++++++++++++++++++++++ discovery/server_test.go | 58 +++++++++---- docs/discovery.schema.json | 148 +++++++++++++++++++++++++++++++++ docs/http-api.md | 2 + go.mod | 1 + go.sum | 4 + orchestrator/discovery_test.go | 85 +++++++++++++++---- orchestrator/pricing_test.go | 21 ----- 8 files changed, 372 insertions(+), 53 deletions(-) create mode 100644 discovery/schema_test.go create mode 100644 docs/discovery.schema.json diff --git a/discovery/schema_test.go b/discovery/schema_test.go new file mode 100644 index 0000000..b69c729 --- /dev/null +++ b/discovery/schema_test.go @@ -0,0 +1,106 @@ +package discovery + +import ( + "bytes" + "encoding/json" + "io" + "os" + "strings" + "testing" + + "github.com/santhosh-tekuri/jsonschema/v6" + "github.com/stretchr/testify/require" +) + +func discoverySchema(t *testing.T) *jsonschema.Schema { + t.Helper() + compiler := jsonschema.NewCompiler() + compiler.AssertFormat() + schema, err := compiler.Compile("../docs/discovery.schema.json") + require.NoError(t, err) + return schema +} + +func validateDiscoveryJSON(t *testing.T, schema *jsonschema.Schema, data []byte) error { + t.Helper() + var value any + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + require.NoError(t, decoder.Decode(&value)) + require.ErrorIs(t, decoder.Decode(&value), io.EOF) + return schema.Validate(value) +} + +func TestDiscoverySchema(t *testing.T) { + schema := discoverySchema(t) + const runner = `{"url":"https://orch.example/app","app":"example","observed_at":"2026-10-22T18:05:00.123+01:00"}` + const metadata = `[{"nodes":[{"url":"https://orch.example","queried_at":"2026-10-22T18:05:00Z"}]}]` + envelope := func(record string) string { + return `[{"address":"https://orch.example/deployment","runners":[` + record + `]}]` + } + for _, test := range []struct { + name, body string + valid bool + }{ + {"empty", `[]`, true}, + {"empty runners", envelope(""), true}, + {"metadata", metadata, true}, + {"metadata with empty runners", `[{"nodes":[],"runners":[]}]`, true}, + {"minimal runner", envelope(runner), true}, + {"IPv6 with port", strings.ReplaceAll(envelope(runner), "orch.example", "[::1]:8935"), true}, + {"mixed-case schemes", strings.ReplaceAll(envelope(runner), "https://", "hTtPs://"), true}, + {"mixed-case node scheme", strings.ReplaceAll(metadata, "https://", "HtTp://"), true}, + {"runner URL components", envelope(strings.ReplaceAll(runner, "https://orch.example/app", "https://user:pass@orch.example/app?x=1#part")), true}, + {"unknown properties", envelope(strings.TrimSuffix(runner, "}") + `,"extension":{"count":9007199254740993}}`), true}, + {"extensible price", envelope(strings.TrimSuffix(runner, "}") + `,"mode":"future","price_info":{"price":123456789012345678901234567890,"price_usd":0.123456789012345678901234567890123456,"currency":"credits","unit":"tokens","extension":true}}`), true}, + {"USD price omitted", envelope(strings.TrimSuffix(runner, "}") + `,"price_info":{"price":1,"currency":"wei","unit":"fixed"}}`), true}, + {"price string", envelope(strings.TrimSuffix(runner, "}") + `,"price_info":{"price":"1"}}`), false}, + {"USD price string", envelope(strings.TrimSuffix(runner, "}") + `,"price_info":{"price":1,"price_usd":"0.1"}}`), false}, + {"missing URL", envelope(strings.ReplaceAll(runner, `"url":"https://orch.example/app",`, "")), false}, + {"missing app", envelope(strings.ReplaceAll(runner, `"app":"example",`, "")), false}, + {"missing observation", envelope(`{"url":"https://orch.example/app","app":"example"}`), false}, + {"empty app", envelope(strings.ReplaceAll(runner, `"app":"example"`, `"app":""`)), false}, + {"invalid observation", envelope(strings.ReplaceAll(runner, "2026-10-22T18:05:00.123+01:00", "yesterday")), false}, + {"invalid query time", `[{"nodes":[{"url":"https://orch.example","queried_at":"yesterday"}]}]`, false}, + {"missing query time", `[{"nodes":[{"url":"https://orch.example"}]}]`, false}, + {"missing node URL", `[{"nodes":[{"queried_at":"2026-10-22T18:05:00Z"}]}]`, false}, + {"metadata with address", `[{"nodes":[],"address":"https://orch.example"}]`, false}, + {"metadata with runners", `[{"nodes":[],"runners":[` + runner + `]}]`, false}, + {"metadata with non-array runners", `[{"nodes":[],"runners":{}}]`, false}, + {"missing runners", `[{"address":"https://orch.example"}]`, false}, + {"non-HTTP address", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "ftp://orch.example"), false}, + {"non-HTTP runner URL", envelope(strings.ReplaceAll(runner, "https://orch.example/app", "ftp://orch.example/app")), false}, + {"address credentials", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "https://user:pass@orch.example/deployment"), false}, + {"address query", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "https://orch.example/deployment?x=1"), false}, + {"address empty query", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "https://orch.example/deployment?"), false}, + {"address fragment", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "https://orch.example/deployment#part"), false}, + {"node credentials", strings.ReplaceAll(metadata, "https://orch.example", "https://user:pass@orch.example"), false}, + {"node query", strings.ReplaceAll(metadata, "https://orch.example", "https://orch.example?x=1"), false}, + {"node fragment", strings.ReplaceAll(metadata, "https://orch.example", "https://orch.example#part"), false}, + {"hostless address", strings.ReplaceAll(envelope(runner), "https://orch.example/deployment", "https://:8935/deployment"), false}, + {"hostless node", strings.ReplaceAll(metadata, "https://orch.example", "https://:8935"), false}, + {"userinfo-only runner", envelope(strings.ReplaceAll(runner, "https://orch.example/app", "https://user:pass@/app")), false}, + } { + t.Run(test.name, func(t *testing.T) { + err := validateDiscoveryJSON(t, schema, []byte(test.body)) + if test.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} + +func TestDiscoverySchemaHTTPExample(t *testing.T) { + doc, err := os.ReadFile("../docs/http-api.md") + require.NoError(t, err) + _, section, ok := strings.Cut(string(doc), "## Discovery HTTP\n") + require.True(t, ok, "Discovery HTTP section must exist") + section, _, _ = strings.Cut(section, "\n## ") + _, block, ok := strings.Cut(section, "```json\n") + require.True(t, ok, "Discovery HTTP must contain a JSON example") + example, _, ok := strings.Cut(block, "\n```") + require.True(t, ok, "JSON example must have a closing fence") + require.NoError(t, validateDiscoveryJSON(t, discoverySchema(t), []byte(example))) +} diff --git a/discovery/server_test.go b/discovery/server_test.go index cab0c78..c018c4c 100644 --- a/discovery/server_test.go +++ b/discovery/server_test.go @@ -210,40 +210,68 @@ func TestDiscoveryFailureThreshold(t *testing.T) { } func TestDiscoveryPreservesWholeRecords(t *testing.T) { - const record = `{"url":"https://orch.example/apps/runner/session","app":"test","observed_at":"2000-01-01T00:00:00.123+00:00","mode":"persistent","capacity":4,"capacity_used":1,"capacity_available":3,"gpu":{"id":"0","name":"H100","vram_mb":80000},"price_info":{"price":123456789012345678901234567890,"currency":"wei","unit":"seconds"},"extension":{"value":9007199254740993}}` - s := discoveryTestServer(t, "https://old.example", "https://child.example", "https://tie.example") + const record = `{"url":"https://orch.example/apps/runner/session","app":"test","observed_at":"2000-01-01T00:00:00.123+00:00","mode":"persistent","capacity":4,"capacity_used":1,"capacity_available":3,"gpu":{"id":"0","name":"H100","vram_mb":80000},"price_info":{"price":123456789012345678901234567890,"price_usd":0.123456789012345678901234567890123456,"currency":"wei","unit":"tokens"},"extension":{"value":9007199254740993,"ratio":1.2300e+04}}` var calls atomic.Int32 - s.collector.Client.Transport = discoveryRoundTrip(func(r *http.Request) (*http.Response, error) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1) owner, runner := "https://orch.example", record - switch r.URL.Host { - case "old.example": + switch r.URL.Path { + case "/old/discovery": owner = "https://old-owner.example" runner = strings.ReplaceAll(runner, "2000-01-01", "1999-01-01") - case "tie.example": + case "/tie/discovery": runner = strings.ReplaceAll(runner, `"app":"test"`, `"app":"tie"`) } - body := `[{"address":"` + owner + `","runners":[` + runner + `]}]` - return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil - }) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `[{"address":"`+owner+`","runners":[`+runner+`]}]`) + })) + defer upstream.Close() + s := discoveryTestServer(t, upstream.URL+"/old", upstream.URL+"/child", upstream.URL+"/tie") var dumped bytes.Buffer require.NoError(t, s.dump(t.Context(), &dumped)) require.Equal(t, int32(3), calls.Load()) + server := httptest.NewServer(s) + defer server.Close() + schema := discoverySchema(t) for range 2 { - w := httptest.NewRecorder() - s.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/discovery", nil)) - require.Equal(t, 200, w.Code) - require.Equal(t, dumped.String(), w.Body.String(), "dump and HTTP share the same snapshot and encoding") + response, err := server.Client().Get(server.URL + "/discovery") + require.NoError(t, err) + data, err := io.ReadAll(response.Body) + require.NoError(t, response.Body.Close()) + require.NoError(t, err) + require.Equal(t, http.StatusOK, response.StatusCode) + require.Equal(t, "application/json", response.Header.Get("Content-Type")) + require.NoError(t, validateDiscoveryJSON(t, schema, data)) + require.Equal(t, dumped.String(), string(data), "dump and HTTP share the same snapshot and encoding") var result []map[string]json.RawMessage - require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + require.NoError(t, json.Unmarshal(data, &result)) require.Len(t, result, 2) require.NotContains(t, result[0], "address") + var nodes []discoveryNode + require.NoError(t, json.Unmarshal(result[0]["nodes"], &nodes)) + require.Len(t, nodes, 3) + require.Equal(t, upstream.URL+"/old", nodes[0].URL) require.Equal(t, `"https://orch.example"`, string(result[1]["address"])) - // Compare raw JSON so large integers cannot be rounded through float64. + // Compare raw JSON to retain unknown fields and exact numeric tokens. require.Equal(t, "["+record+"]", string(result[1]["runners"])) } } +func TestDiscoveryEmptyInventory(t *testing.T) { + s := discoveryTestServer(t) + server := httptest.NewServer(s) + defer server.Close() + response, err := server.Client().Get(server.URL + "/discovery") + require.NoError(t, err) + defer response.Body.Close() + require.Equal(t, http.StatusOK, response.StatusCode) + require.Equal(t, "application/json", response.Header.Get("Content-Type")) + data, err := io.ReadAll(response.Body) + require.NoError(t, err) + require.JSONEq(t, `[]`, string(data)) + require.NoError(t, validateDiscoveryJSON(t, discoverySchema(t), data)) +} + func TestDiscoveryPrivateSourcesRequireGrants(t *testing.T) { var calls atomic.Int32 upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { diff --git a/docs/discovery.schema.json b/docs/discovery.schema.json new file mode 100644 index 0000000..f6ba370 --- /dev/null +++ b/docs/discovery.schema.json @@ -0,0 +1,148 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "GET /discovery response", + "description": "A forwarding contract for orchestrator and standalone discovery inventories. Empty arrays are successful inventories. Aggregators must preserve complete runner records, including unknown properties and the lexical form of numeric tokens. Timestamp freshness and tolerant record skipping are runtime checks, not schema constraints.", + "type": "array", + "items": { + "oneOf": [ + { "$ref": "#/$defs/metadataEntry" }, + { "$ref": "#/$defs/orchestratorEntry" } + ] + }, + "$defs": { + "httpURL": { + "type": "string", + "format": "uri", + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://([^/?#@]*@)?[^/?#@:][^/?#@]*([/?#]|$)" + }, + "baseURL": { + "$ref": "#/$defs/httpURL", + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@]+(/[^?#]*)?$", + "description": "An HTTP(S) base URL without credentials, query, or fragment; deployment paths are allowed." + }, + "metadataEntry": { + "type": "object", + "description": "Standalone discovery prepends this entry only when it advertises successfully queried, non-evicted sources.", + "required": ["nodes"], + "not": { "required": ["address"] }, + "properties": { + "runners": { "type": "array", "maxItems": 0 }, + "nodes": { + "type": "array", + "items": { "$ref": "#/$defs/node" } + } + }, + "additionalProperties": true + }, + "node": { + "type": "object", + "required": ["url", "queried_at"], + "properties": { + "url": { + "$ref": "#/$defs/baseURL", + "description": "The queried source's HTTP(S) base URL." + }, + "queried_at": { + "type": "string", + "format": "date-time", + "description": "RFC 3339 time of the source's last successful query." + } + }, + "additionalProperties": true + }, + "orchestratorEntry": { + "type": "object", + "required": ["address", "runners"], + "properties": { + "address": { + "$ref": "#/$defs/baseURL", + "description": "The owning orchestrator's HTTP(S) base URL, including any deployment path; not an Ethereum address." + }, + "runners": { + "type": "array", + "items": { "$ref": "#/$defs/runner" } + } + }, + "additionalProperties": true + }, + "runner": { + "type": "object", + "description": "A ready app. Aggregators must forward unknown properties.", + "required": ["url", "app", "observed_at"], + "properties": { + "url": { + "$ref": "#/$defs/httpURL", + "description": "The app endpoint advertised by the owning orchestrator." + }, + "app": { + "type": "string", + "minLength": 1, + "description": "Application name." + }, + "observed_at": { + "type": "string", + "format": "date-time", + "description": "RFC 3339 observation time, allowing fractional seconds. Orchestrators stamp local runners at response time; aggregators preserve the timestamp." + }, + "version": { + "type": "string", + "description": "Application version." + }, + "metadata": { + "type": "string", + "description": "Application-supplied metadata." + }, + "gpu": { "$ref": "#/$defs/gpu" }, + "mode": { + "type": "string", + "description": "This orchestrator emits persistent or single-shot; discovery forwards other upstream values unchanged." + }, + "capacity": { + "type": "integer", + "description": "Configured concurrent session capacity." + }, + "capacity_used": { + "type": "integer", + "description": "Currently reserved sessions." + }, + "capacity_available": { + "type": "integer", + "description": "Capacity currently available for new sessions." + }, + "price_info": { "$ref": "#/$defs/priceInfo" } + }, + "additionalProperties": true + }, + "gpu": { + "type": "object", + "properties": { + "id": { "type": "string", "description": "GPU identifier." }, + "name": { "type": "string", "description": "GPU name." }, + "vram_mb": { "type": "integer", "description": "GPU memory in MB." } + }, + "additionalProperties": true + }, + "priceInfo": { + "type": "object", + "properties": { + "price": { + "type": "number", + "description": "Price per advertised unit in the advertised currency. Consumers must preserve the exact JSON numeric token without rounding through binary floating point." + }, + "price_usd": { + "type": "number", + "description": "Optional registered USD price per advertised unit. Consumers must preserve the exact JSON numeric token without rounding through binary floating point. On-chain orchestrators divide hourly quotes by 3600 for the seconds unit and leave fixed quotes unchanged, with up to 36 fractional digits and trailing zeros trimmed." + }, + "currency": { + "type": "string", + "description": "This orchestrator emits wei; discovery forwards other upstream currencies unchanged." + }, + "unit": { + "type": "string", + "description": "This orchestrator emits seconds or fixed; discovery forwards other upstream units unchanged." + } + }, + "additionalProperties": true + } + } +} diff --git a/docs/http-api.md b/docs/http-api.md index 4267c41..c0cdb61 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -43,6 +43,8 @@ behavior, and proxy routes. ## Discovery HTTP +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 diff --git a/go.mod b/go.mod index 0ca3ed0..f2c91d3 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/j0sh/minikafka v0.0.0-20261001174935-0bc8dcedd322 github.com/prometheus/client_golang v1.25.0 github.com/prometheus/client_model v0.6.3 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 github.com/segmentio/kafka-go v0.4.51 github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.12.1 diff --git a/go.sum b/go.sum index ac9f239..d341019 100644 --- a/go.sum +++ b/go.sum @@ -58,6 +58,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/deepmap/oapi-codegen v1.6.0 h1:w/d1ntwh91XI0b/8ja7+u5SvA4IFfM0UNNLmiDR1gg0= github.com/deepmap/oapi-codegen v1.6.0/go.mod h1:ryDa9AgbELGeB+YEXE1dR53yAjHwFvE9iAUlWl9Al3M= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A= @@ -204,6 +206,8 @@ github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/segmentio/kafka-go v0.4.51 h1:JgDPPG75tC1rWIS2Me6MwcvXJ6f49UQ4HjAOef71Hno= github.com/segmentio/kafka-go v0.4.51/go.mod h1:Y1gn60kzLEEaW28YshXyk2+VCUKbJ3Qr6DrnT3i4+9E= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU= diff --git a/orchestrator/discovery_test.go b/orchestrator/discovery_test.go index 116dd96..c80c718 100644 --- a/orchestrator/discovery_test.go +++ b/orchestrator/discovery_test.go @@ -1,35 +1,86 @@ package orchestrator import ( + "bytes" "encoding/json" "io" "log/slog" + "math/big" "net/http" "net/http/httptest" "testing" "time" "github.com/livepeer/node/destination" + "github.com/santhosh-tekuri/jsonschema/v6" "github.com/stretchr/testify/require" ) func TestDiscoveryLocalInventory(t *testing.T) { - registry := NewRegistry("bootstrap", "https://orch.example/deployment", time.Second, time.Minute) - require.NoError(t, registry.AddStatic(StaticRunner{ID: "local", RunnerURL: "http://127.0.0.1:9000", App: "local", Mode: "single-shot", Capacity: 2})) - policy, err := destination.New("test", nil) + compiler := jsonschema.NewCompiler() + compiler.AssertFormat() + schema, err := compiler.Compile("../docs/discovery.schema.json") require.NoError(t, err) - s := NewServer(registry, policy, policy, slog.New(slog.NewTextHandler(io.Discard, nil))) - defer s.Close() - w := httptest.NewRecorder() - s.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/deployment/discovery", nil)) - require.Equal(t, 200, w.Code) - require.NotContains(t, w.Body.String(), `"nodes"`) - require.NotContains(t, w.Body.String(), `"app_id"`) - require.NotContains(t, w.Body.String(), `"runner_id"`) - var entries []discoveryEntry - require.NoError(t, json.Unmarshal(w.Body.Bytes(), &entries)) - require.Len(t, entries, 1) - require.Equal(t, registry.service, entries[0].Address) - require.Len(t, entries[0].Runners, 1) - require.Equal(t, "https://orch.example/deployment/apps/local/app", entries[0].Runners[0].URL) + for _, inventory := range []string{"empty", "offchain", "onchain"} { + t.Run(inventory, func(t *testing.T) { + registry := NewRegistry("bootstrap", "https://orch.example/deployment", time.Second, time.Minute) + if inventory == "onchain" { + registry.SetWeiPerUSD(big.NewRat(3600, 1)) + } + if inventory != "empty" { + require.NoError(t, registry.AddStatic(StaticRunner{ + ID: "local", RunnerURL: "http://127.0.0.1:9000", App: "local", Mode: "single-shot", Capacity: 2, + Version: "v1", Metadata: "model-x", GPU: &runnerGPU{ID: "0", Name: "H100", VRAMMB: 80000}, + PriceInfo: priceInfo{Price: "1", Currency: "usd", Unit: "hour"}, + })) + } + policy, err := destination.New("test", nil) + require.NoError(t, err) + s := NewServer(registry, policy, policy, slog.New(slog.NewTextHandler(io.Discard, nil))) + t.Cleanup(s.Close) + server := httptest.NewServer(s) + t.Cleanup(server.Close) + response, err := server.Client().Get(server.URL + "/deployment/discovery") + require.NoError(t, err) + defer response.Body.Close() + require.Equal(t, http.StatusOK, response.StatusCode) + require.Equal(t, "application/json", response.Header.Get("Content-Type")) + data, err := io.ReadAll(response.Body) + require.NoError(t, err) + var value any + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + require.NoError(t, decoder.Decode(&value)) + require.ErrorIs(t, decoder.Decode(&value), io.EOF) + require.NoError(t, schema.Validate(value)) + require.NotContains(t, string(data), `"nodes"`) + require.NotContains(t, string(data), `"app_id"`) + require.NotContains(t, string(data), `"runner_id"`) + var entries []discoveryEntry + require.NoError(t, json.Unmarshal(data, &entries)) + require.Len(t, entries, 1) + require.Equal(t, registry.service, entries[0].Address) + if inventory == "empty" { + require.NotNil(t, entries[0].Runners) + require.Empty(t, entries[0].Runners) + return + } + require.Len(t, entries[0].Runners, 1) + runner := entries[0].Runners[0] + require.Equal(t, "https://orch.example/deployment/apps/local/app", runner.URL) + require.Equal(t, "local", runner.App) + require.Equal(t, "v1", runner.Version) + require.Equal(t, "model-x", runner.Metadata) + require.Equal(t, &runnerGPU{ID: "0", Name: "H100", VRAMMB: 80000}, runner.GPU) + require.Equal(t, "single-shot", runner.Mode) + require.Equal(t, 2, runner.Capacity) + require.Zero(t, runner.CapacityUsed) + require.Equal(t, 2, runner.CapacityAvailable) + if inventory == "onchain" { + require.Equal(t, priceInfo{Price: "1", PriceUSD: "0.000277777777777777777777777777777778", Currency: "wei", Unit: "seconds"}, runner.PriceInfo) + } else { + require.NotContains(t, string(data), `"price_info"`) + } + }) + } } diff --git a/orchestrator/pricing_test.go b/orchestrator/pricing_test.go index fb5198d..61e8bb5 100644 --- a/orchestrator/pricing_test.go +++ b/orchestrator/pricing_test.go @@ -1,9 +1,7 @@ package orchestrator import ( - "encoding/json" "math/big" - "strings" "testing" "testing/synctest" "time" @@ -12,25 +10,6 @@ import ( "github.com/stretchr/testify/require" ) -func TestDiscoveryOmitsOffchainPriceInfo(t *testing.T) { - for name, paid := range map[string]bool{"offchain": false, "onchain": true} { - t.Run(name, func(t *testing.T) { - r := NewRegistry("", "https://orch.example", time.Second, time.Minute) - if paid { - r.SetWeiPerUSD(big.NewRat(10, 1)) - } - require.NoError(t, r.AddStatic(StaticRunner{ID: "r", RunnerURL: "https://runner.example", App: "app", PriceInfo: priceInfo{Price: "1", Unit: "fixed", Currency: "usd"}})) - - entries := r.Discovery() - require.Len(t, entries, 1) - require.Len(t, entries[0].Runners, 1) - data, err := json.Marshal(entries) - require.NoError(t, err) - require.Equal(t, paid, strings.Contains(string(data), `"price_info":`), "price_info presence in discovery JSON") - }) - } -} - func TestFeedUpdatesOnlyNewSessionPricesAndFailsClosedWhenStale(t *testing.T) { synctest.Test(t, func(t *testing.T) { r := NewRegistry("secret", "https://orch.example", time.Second, time.Minute)