api: POST /api/scenario returns result plus graph topology (M3 slice 1)
One panel's whole world in one call: effective config in, echoed config + cascade result + undirected edge list out. Edges are [from, to] pairs with from < to in deterministic node order; Graph.Edges() walks the adjacency once, GraphEdges(config) rebuilds the seeded world (~25us) so Result stays lean and /api/comparison stays untouched. This closes the topology gap the design brief flagged; the frontend's seeded d3-force layout consumes these pairs. Go bits: [][2]int is a slice of fixed-size arrays; [2]int is a value type, comparable, and JSON-marshals to [a, b], exactly the wire shape the spec asks for. tygo regen includes a fix: engine.Strategy now maps to the generated Strategy type instead of decaying to 'any' in ScenarioRequest. Verified live through the dev stack: 7/120 reached, 351 edges.
This commit is contained in:
parent
8c8d5bca11
commit
9a392b1860
12 changed files with 1790 additions and 2 deletions
|
|
@ -19,6 +19,23 @@ type ComparisonResponse struct {
|
|||
Results []engine.Result `json:"results"`
|
||||
}
|
||||
|
||||
// ScenarioRequest is the body of POST /api/scenario: one panel's effective
|
||||
// config plus its strategy.
|
||||
type ScenarioRequest struct {
|
||||
Config engine.Config `json:"config"`
|
||||
Strategy engine.Strategy `json:"strategy"`
|
||||
}
|
||||
|
||||
// ScenarioResponse carries everything one dashboard panel needs: the
|
||||
// echoed config, the cascade result, and the network topology as
|
||||
// [from, to] node-index pairs (deterministic from the config's graph
|
||||
// fields) for the frontend's force layout.
|
||||
type ScenarioResponse struct {
|
||||
Config engine.Config `json:"config"`
|
||||
Result engine.Result `json:"result"`
|
||||
Edges [][2]int `json:"edges"`
|
||||
}
|
||||
|
||||
// errorResponse is the JSON shape of every non-2xx body.
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
|
|
@ -31,6 +48,7 @@ func NewServer() http.Handler {
|
|||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/config/default", handleDefaultConfig)
|
||||
mux.HandleFunc("POST /api/comparison", handleComparison)
|
||||
mux.HandleFunc("POST /api/scenario", handleScenario)
|
||||
return mux
|
||||
}
|
||||
|
||||
|
|
@ -62,6 +80,30 @@ func handleComparison(w http.ResponseWriter, r *http.Request) {
|
|||
writeJSON(w, http.StatusOK, ComparisonResponse{Config: config, Results: results})
|
||||
}
|
||||
|
||||
func handleScenario(w http.ResponseWriter, r *http.Request) {
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
var request ScenarioRequest
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
writeError(w, http.StatusBadRequest, fmt.Errorf("invalid request: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
result, err := engine.RunScenario(request.Config, request.Strategy)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
// Building the graph again for its edges costs ~25us (seeded, so it is
|
||||
// the identical world the scenario ran in).
|
||||
edges, err := engine.GraphEdges(request.Config)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, ScenarioResponse{Config: request.Config, Result: result, Edges: edges})
|
||||
}
|
||||
|
||||
// writeJSON marshals first and writes after, so an encoding failure can
|
||||
// still become a clean 500 instead of a half-written body.
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
|
|
|
|||
87
internal/api/scenario_test.go
Normal file
87
internal/api/scenario_test.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/JustinZeus/spreadlab/internal/engine"
|
||||
)
|
||||
|
||||
func postScenario(t *testing.T, request ScenarioRequest) *json.Decoder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder := serve(t, http.MethodPost, "/api/scenario", body)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body: %s", recorder.Code, http.StatusOK, recorder.Body)
|
||||
}
|
||||
return json.NewDecoder(recorder.Body)
|
||||
}
|
||||
|
||||
func TestScenarioEndpointReturnsResultAndTopology(t *testing.T) {
|
||||
request := ScenarioRequest{Config: engine.DefaultConfig(), Strategy: engine.StrategyMostConnected}
|
||||
|
||||
var response ScenarioResponse
|
||||
if err := postScenario(t, request).Decode(&response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if response.Result.NumReached != 7 { // the pinned golden value
|
||||
t.Errorf("NumReached = %d, want 7", response.Result.NumReached)
|
||||
}
|
||||
if response.Config != request.Config {
|
||||
t.Errorf("config not echoed: got %+v", response.Config)
|
||||
}
|
||||
if len(response.Edges) == 0 {
|
||||
t.Fatal("no edges returned")
|
||||
}
|
||||
for _, edge := range response.Edges {
|
||||
if edge[0] >= edge[1] || edge[1] >= request.Config.NumStudents {
|
||||
t.Fatalf("invalid edge %v", edge)
|
||||
}
|
||||
}
|
||||
|
||||
// Determinism across requests is the shared-URL guarantee.
|
||||
var repeat ScenarioResponse
|
||||
if err := postScenario(t, request).Decode(&repeat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(repeat.Edges) != len(response.Edges) || repeat.Edges[0] != response.Edges[0] {
|
||||
t.Error("edges differ across identical requests")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScenarioEndpointRejectsBadRequests(t *testing.T) {
|
||||
valid := engine.DefaultConfig()
|
||||
invalid := valid
|
||||
invalid.ForwardProb = 2.0
|
||||
|
||||
encode := func(request ScenarioRequest) []byte {
|
||||
body, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body []byte
|
||||
}{
|
||||
{name: "not json", body: []byte("not json")},
|
||||
{name: "unknown field", body: []byte(`{"config":{},"strategy":"none","extra":1}`)},
|
||||
{name: "unknown strategy", body: encode(ScenarioRequest{Config: valid, Strategy: "telepathy"})},
|
||||
{name: "invalid config values", body: encode(ScenarioRequest{Config: invalid, Strategy: engine.StrategyNone})},
|
||||
}
|
||||
for _, testCase := range tests {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
recorder := serve(t, http.MethodPost, "/api/scenario", testCase.body)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want %d; body: %s", recorder.Code, http.StatusBadRequest, recorder.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -48,3 +48,18 @@ func (g *Graph) Degree(u int) int { return len(g.adj[u]) }
|
|||
// Neighbors returns u's neighbours in insertion order. The slice is the
|
||||
// graph's own storage: callers must not modify it.
|
||||
func (g *Graph) Neighbors(u int) []int { return g.adj[u] }
|
||||
|
||||
// Edges returns every undirected edge exactly once as a [from, to] pair
|
||||
// with from < to, in deterministic node order. The slice is freshly
|
||||
// allocated; callers may keep it.
|
||||
func (g *Graph) Edges() [][2]int {
|
||||
edges := make([][2]int, 0, g.edges)
|
||||
for node := range g.NumNodes() {
|
||||
for _, neighbor := range g.adj[node] {
|
||||
if node < neighbor {
|
||||
edges = append(edges, [2]int{node, neighbor})
|
||||
}
|
||||
}
|
||||
}
|
||||
return edges
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,3 +74,56 @@ func TestGraphNeighborsAndDegree(t *testing.T) {
|
|||
t.Error("HasEdge(1, 2) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphEdgesListsEveryEdgeOnce(t *testing.T) {
|
||||
graph := NewGraph(4)
|
||||
graph.AddEdge(2, 1) // insertion order must not matter; pairs come out from < to
|
||||
graph.AddEdge(0, 1)
|
||||
graph.AddEdge(3, 0)
|
||||
|
||||
want := [][2]int{{0, 1}, {0, 3}, {1, 2}}
|
||||
if got := graph.Edges(); !slices.Equal(got, want) {
|
||||
t.Errorf("Edges() = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphEdgesMatchesGeneratedGraph(t *testing.T) {
|
||||
graph, err := HolmeKim(60, 3, 0.45, newRand(17))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
edges := graph.Edges()
|
||||
if len(edges) != graph.NumEdges() {
|
||||
t.Fatalf("len(Edges()) = %d, want NumEdges() = %d", len(edges), graph.NumEdges())
|
||||
}
|
||||
for _, edge := range edges {
|
||||
from, to := edge[0], edge[1]
|
||||
if from >= to {
|
||||
t.Errorf("edge %v: want from < to", edge)
|
||||
}
|
||||
if to >= graph.NumNodes() {
|
||||
t.Errorf("edge %v: endpoint out of range", edge)
|
||||
}
|
||||
if !graph.HasEdge(from, to) {
|
||||
t.Errorf("edge %v not present in adjacency", edge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphEdgesDeterministicFromConfig(t *testing.T) {
|
||||
first, err := GraphEdges(DefaultConfig())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := GraphEdges(DefaultConfig())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(first, second) {
|
||||
t.Error("GraphEdges() differs across identical configs")
|
||||
}
|
||||
if len(first) == 0 {
|
||||
t.Error("GraphEdges() returned no edges")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,6 +60,18 @@ type Result struct {
|
|||
ReachedPct float64 `json:"reachedPct"`
|
||||
}
|
||||
|
||||
// GraphEdges builds the world's social network from the config's graph
|
||||
// fields and returns its undirected edge list. The same config always
|
||||
// yields the same edges (seeded generator), so the API can expose
|
||||
// topology separately without every Result carrying it.
|
||||
func GraphEdges(config Config) ([][2]int, error) {
|
||||
graph, err := HolmeKim(config.NumStudents, config.EdgesPerNode, config.TriangleProb, newRand(config.GraphSeed))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return graph.Edges(), nil
|
||||
}
|
||||
|
||||
// RunScenario builds the world the config describes (network plus edge
|
||||
// thresholds), picks the educated students per strategy, and runs the
|
||||
// cascade. Scenarios with the same config share the same world, so
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue