diff --git a/README.md b/README.md index b2b8c09..8cf4353 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ first snapshot arrives. Control endpoints return `503` until `CONTROL_USER` and | `GET /api/series` | Observed series; query `sensor`, `from`, `to`, `step=15m\|1h`. | | `GET /api/context` | Weather and holidays. | | `GET /api/forecast` | Live forecast or last-good fallback; query `sensor`, `horizon`, `scenario`. | +| `GET /api/playground/forecast` | Read-only forecast with optional `temp_c`, `precip_mm`, `is_holiday`; never mutates scenario state. | | `GET /api/staffing` | Shift plan; query `sensor`, `scenario`, `standard`. | | `GET /api/scenario` | Current scenario. | | `POST /api/scenario` | Set scenario (control auth) and broadcast it over SSE. | diff --git a/internal/api/handlers_playground.go b/internal/api/handlers_playground.go new file mode 100644 index 0000000..3ae8b85 --- /dev/null +++ b/internal/api/handlers_playground.go @@ -0,0 +1,170 @@ +package api + +import ( + "context" + "fmt" + "log/slog" + "math" + "net/http" + "strconv" + + "pulsecast/api/internal/ml" + "pulsecast/api/internal/model" +) + +// PlaygroundClient is the optional FastAPI playground surface. It is separate +// from MLClient so existing prediction-only stubs and handlers keep working. +type PlaygroundClient interface { + PlaygroundPredict(ctx context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) +} + +// handlePlaygroundForecast is a read-only, public forecast endpoint with +// optional weather and holiday overrides. It never mutates the global scenario +// state used by /live, /stage, or /cool. +func (s *Server) handlePlaygroundForecast(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + sensor := query.Get("sensor") + if sensor == "" { + writeError(w, http.StatusBadRequest, "bad_request", "sensor is required") + return + } + if s.cache == nil { + writeError(w, http.StatusNotFound, "not_found", "unknown sensor") + return + } + if _, ok := s.cache.Sensor(sensor); !ok { + writeError(w, http.StatusNotFound, "not_found", "unknown sensor") + return + } + + horizon := query.Get("horizon") + if horizon == "" { + horizon = "48h" + } + if !model.Contains(model.Horizons, horizon) { + writeError(w, http.StatusBadRequest, "bad_request", "horizon must be one of 15m, 1h, 48h, 7d") + return + } + + scenarioName := query.Get("scenario") + if scenarioName == "" { + scenarioName = "base" + } + if !model.Contains(model.Scenarios, scenarioName) { + writeError(w, http.StatusBadRequest, "bad_request", "unknown scenario") + return + } + + tempC, err := optionalFloat(query.Get("temp_c"), "temp_c") + if err != nil { + writeError(w, http.StatusBadRequest, "bad_request", err.Error()) + return + } + if tempC != nil && (*tempC < -30 || *tempC > 50) { + writeError(w, http.StatusBadRequest, "bad_request", "temp_c must be between -30 and 50") + return + } + + precipMM, err := optionalFloat(query.Get("precip_mm"), "precip_mm") + if err != nil { + writeError(w, http.StatusBadRequest, "bad_request", err.Error()) + return + } + if precipMM != nil && (*precipMM < 0 || *precipMM > 50) { + writeError(w, http.StatusBadRequest, "bad_request", "precip_mm must be between 0 and 50") + return + } + + isHoliday, err := optionalBool(query.Get("is_holiday")) + if err != nil { + writeError(w, http.StatusBadRequest, "bad_request", "is_holiday must be a boolean") + return + } + + client, ok := s.ml.(PlaygroundClient) + if !ok || client == nil { + writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI prediction is unavailable") + return + } + + var weather *ml.PlaygroundWeather + if tempC != nil || precipMM != nil { + weather = &ml.PlaygroundWeather{TempC: tempC, PrecipMM: precipMM} + } + + ctx, cancel := context.WithTimeout(r.Context(), s.cfg.MLTimeout) + defer cancel() + + result, err := client.PlaygroundPredict(ctx, ml.PlaygroundRequest{ + Sensor: sensor, + Horizon: horizon, + Scenario: scenarioName, + Weather: weather, + IsHoliday: isHoliday, + }) + if err != nil { + slog.Warn("playground prediction failed", "sensor", sensor, "scenario", scenarioName, "error", err) + writeError(w, http.StatusBadGateway, "ml_unavailable", "FastAPI prediction is unavailable") + return + } + + weatherSource := "forecast" + if weather != nil { + weatherSource = "override" + } + + w.Header().Set("X-Data-Version", result.DataVersion) + w.Header().Set("X-Model-Version", result.ModelVersion) + w.Header().Set("X-Context-Version", result.ContextVersion) + writeJSON(w, http.StatusOK, struct { + Sensor string `json:"sensor"` + Horizon string `json:"horizon"` + Scenario string `json:"scenario"` + Points []model.ForecastPoint `json:"points"` + DataVersion string `json:"data_version"` + ModelVersion string `json:"model_version"` + ContextVersion string `json:"context_version"` + WeatherSource string `json:"weather_source"` + Request struct { + TempC *float64 `json:"temp_c,omitempty"` + PrecipMM *float64 `json:"precip_mm,omitempty"` + IsHoliday *bool `json:"is_holiday,omitempty"` + } `json:"request"` + }{ + Sensor: result.Sensor, + Horizon: result.Horizon, + Scenario: result.Scenario, + Points: result.Points, + DataVersion: result.DataVersion, + ModelVersion: result.ModelVersion, + ContextVersion: result.ContextVersion, + WeatherSource: weatherSource, + Request: struct { + TempC *float64 `json:"temp_c,omitempty"` + PrecipMM *float64 `json:"precip_mm,omitempty"` + IsHoliday *bool `json:"is_holiday,omitempty"` + }{TempC: tempC, PrecipMM: precipMM, IsHoliday: isHoliday}, + }) +} + +func optionalFloat(raw, name string) (*float64, error) { + if raw == "" { + return nil, nil + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil || math.IsNaN(value) || math.IsInf(value, 0) { + return nil, fmt.Errorf("%s must be a number", name) + } + return &value, nil +} + +func optionalBool(raw string) (*bool, error) { + if raw == "" { + return nil, nil + } + value, err := strconv.ParseBool(raw) + if err != nil { + return nil, err + } + return &value, nil +} diff --git a/internal/api/handlers_playground_test.go b/internal/api/handlers_playground_test.go new file mode 100644 index 0000000..abfe0ee --- /dev/null +++ b/internal/api/handlers_playground_test.go @@ -0,0 +1,200 @@ +package api + +import ( + "context" + "errors" + "net/http" + "strings" + "testing" + "time" + + "pulsecast/api/internal/ml" + "pulsecast/api/internal/model" +) + +type stubPlayground struct { + *stubML + fn func(context.Context, ml.PlaygroundRequest) (ml.PlaygroundResponse, error) +} + +func (s *stubPlayground) PlaygroundPredict(ctx context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) { + if s.fn == nil { + return ml.PlaygroundResponse{}, errors.New("ml unavailable") + } + return s.fn(ctx, req) +} + +func playgroundResponse() ml.PlaygroundResponse { + return ml.PlaygroundResponse{ + Sensor: "hn-bahnhof-01", + Horizon: "48h", + Scenario: "base", + Points: []model.ForecastPoint{{ + T: time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC), V: 12.3, Lo: 8.1, Hi: 17.2, + }}, + DataVersion: "data-1", + ModelVersion: "model-1", + ContextVersion: "context-1", + } +} + +type playgroundJSON struct { + Sensor string `json:"sensor"` + Horizon string `json:"horizon"` + Scenario string `json:"scenario"` + Points []model.ForecastPoint `json:"points"` + DataVersion string `json:"data_version"` + ModelVersion string `json:"model_version"` + ContextVersion string `json:"context_version"` + WeatherSource string `json:"weather_source"` + Request struct { + TempC *float64 `json:"temp_c"` + PrecipMM *float64 `json:"precip_mm"` + IsHoliday *bool `json:"is_holiday"` + } `json:"request"` +} + +func TestPlaygroundForecastDefaults(t *testing.T) { + var got ml.PlaygroundRequest + client := &stubPlayground{ + stubML: &stubML{}, + fn: func(_ context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) { + got = req + return playgroundResponse(), nil + }, + } + _, ts := newTestServer(t, client, nil) + + var payload playgroundJSON + resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &payload) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status=%d", resp.StatusCode) + } + if got.Horizon != "48h" || got.Scenario != "base" { + t.Fatalf("defaults horizon=%q scenario=%q", got.Horizon, got.Scenario) + } + if got.Weather != nil || got.IsHoliday != nil { + t.Fatalf("unexpected overrides: weather=%+v holiday=%v", got.Weather, got.IsHoliday) + } + if payload.WeatherSource != "forecast" { + t.Errorf("weather_source=%q", payload.WeatherSource) + } + if payload.ModelVersion != "model-1" || payload.DataVersion != "data-1" || payload.ContextVersion != "context-1" { + t.Fatalf("versions=%+v", payload) + } + if resp.Header.Get("X-Model-Version") != "model-1" { + t.Errorf("X-Model-Version=%q", resp.Header.Get("X-Model-Version")) + } + if len(payload.Points) != 1 || payload.Points[0].V != 12.3 { + t.Fatalf("points=%+v", payload.Points) + } +} + +func TestPlaygroundForecastOverrides(t *testing.T) { + var got ml.PlaygroundRequest + client := &stubPlayground{ + stubML: &stubML{}, + fn: func(_ context.Context, req ml.PlaygroundRequest) (ml.PlaygroundResponse, error) { + got = req + return playgroundResponse(), nil + }, + } + _, ts := newTestServer(t, client, nil) + + var payload playgroundJSON + resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=29&precip_mm=0&is_holiday=true", &payload) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status=%d", resp.StatusCode) + } + if got.Weather == nil || got.Weather.TempC == nil || *got.Weather.TempC != 29 { + t.Fatalf("weather=%+v", got.Weather) + } + if got.Weather.PrecipMM == nil || *got.Weather.PrecipMM != 0 { + t.Fatalf("precip=%+v", got.Weather.PrecipMM) + } + if got.IsHoliday == nil || !*got.IsHoliday { + t.Fatalf("holiday=%+v", got.IsHoliday) + } + if payload.WeatherSource != "override" { + t.Errorf("weather_source=%q", payload.WeatherSource) + } + if payload.Request.TempC == nil || *payload.Request.TempC != 29 { + t.Errorf("request echo temp=%+v", payload.Request.TempC) + } + if payload.Request.IsHoliday == nil || !*payload.Request.IsHoliday { + t.Errorf("request echo holiday=%+v", payload.Request.IsHoliday) + } +} + +func TestPlaygroundForecastValidation(t *testing.T) { + _, ts := newTestServer(t, &stubPlayground{stubML: &stubML{}}, nil) + cases := []struct { + path string + status int + code string + }{ + {"/api/playground/forecast", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=nope", http.StatusNotFound, "not_found"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&horizon=2h", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&scenario=party", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=hot", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=51", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&temp_c=NaN", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&precip_mm=-1", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&precip_mm=51", http.StatusBadRequest, "bad_request"}, + {"/api/playground/forecast?sensor=hn-bahnhof-01&is_holiday=maybe", http.StatusBadRequest, "bad_request"}, + } + for _, tc := range cases { + var body model.ErrorBody + resp := getJSON(t, ts.URL+tc.path, &body) + if resp.StatusCode != tc.status { + t.Errorf("%s: status=%d, want %d", tc.path, resp.StatusCode, tc.status) + } + if body.Error.Code != tc.code { + t.Errorf("%s: code=%q, want %q", tc.path, body.Error.Code, tc.code) + } + } +} + +func TestPlaygroundForecastUpstreamFailure(t *testing.T) { + client := &stubPlayground{ + stubML: &stubML{}, + fn: func(context.Context, ml.PlaygroundRequest) (ml.PlaygroundResponse, error) { + return ml.PlaygroundResponse{}, errors.New("connection refused") + }, + } + _, ts := newTestServer(t, client, nil) + + var body model.ErrorBody + resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &body) + if resp.StatusCode != http.StatusBadGateway { + t.Fatalf("status=%d, want 502", resp.StatusCode) + } + if body.Error.Code != "ml_unavailable" { + t.Fatalf("error=%+v", body.Error) + } +} + +func TestPlaygroundForecastMethodNotAllowed(t *testing.T) { + _, ts := newTestServer(t, &stubPlayground{stubML: &stubML{}}, nil) + resp, err := http.Post(ts.URL+"/api/playground/forecast", "application/json", strings.NewReader("{}")) + if err != nil { + t.Fatalf("POST: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("status=%d, want 405", resp.StatusCode) + } +} + +func TestPlaygroundForecastMissingMLClient(t *testing.T) { + _, ts := newTestServer(t, &stubML{}, nil) + var body model.ErrorBody + resp := getJSON(t, ts.URL+"/api/playground/forecast?sensor=hn-bahnhof-01", &body) + if resp.StatusCode != http.StatusBadGateway { + t.Fatalf("status=%d, want 502", resp.StatusCode) + } + if body.Error.Code != "ml_unavailable" { + t.Fatalf("error=%+v", body.Error) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 056cea2..2a34a68 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -98,6 +98,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/series", s.handleSeries) mux.HandleFunc("GET /api/context", s.handleContext) mux.HandleFunc("GET /api/forecast", s.handleForecast) + mux.HandleFunc("GET /api/playground/forecast", s.handlePlaygroundForecast) mux.HandleFunc("GET /api/staffing", s.handleStaffing) mux.HandleFunc("GET /api/scenario", s.handleScenarioGet) mux.HandleFunc("POST /api/scenario", s.requireControlAuth(s.handleScenarioPost)) @@ -112,19 +113,20 @@ func (s *Server) Handler() http.Handler { } var methodTable = map[string][]string{ - "/api/healthz": {"GET"}, - "/api/readyz": {"GET"}, - "/api/meta": {"GET"}, - "/api/sensors": {"GET"}, - "/api/series": {"GET"}, - "/api/context": {"GET"}, - "/api/forecast": {"GET"}, - "/api/staffing": {"GET"}, - "/api/scenario": {"GET", "POST"}, - "/api/train": {"POST"}, - "/api/prezero/summary": {"GET"}, - "/api/prezero/priority": {"GET"}, - "/api/stream": {"GET"}, + "/api/healthz": {"GET"}, + "/api/readyz": {"GET"}, + "/api/meta": {"GET"}, + "/api/sensors": {"GET"}, + "/api/series": {"GET"}, + "/api/context": {"GET"}, + "/api/forecast": {"GET"}, + "/api/playground/forecast": {"GET"}, + "/api/staffing": {"GET"}, + "/api/scenario": {"GET", "POST"}, + "/api/train": {"POST"}, + "/api/prezero/summary": {"GET"}, + "/api/prezero/priority": {"GET"}, + "/api/stream": {"GET"}, } // routeCheck keeps unknown routes and methods in the JSON error envelope; diff --git a/internal/ml/client.go b/internal/ml/client.go index 5b09e36..158c5a7 100644 --- a/internal/ml/client.go +++ b/internal/ml/client.go @@ -107,6 +107,36 @@ type WeatherInput struct { PrecipMM float64 `json:"precip_mm"` } +// PlaygroundWeather is the optional absolute weather override for the +// playground. Pointers distinguish "not supplied" from a real zero value. +type PlaygroundWeather struct { + TempC *float64 `json:"temp_c,omitempty"` + PrecipMM *float64 `json:"precip_mm,omitempty"` +} + +// PlaygroundRequest is the public playground's prediction request. Weather is +// omitted entirely when the caller did not override it, so Python uses its +// baked hourly weather forecast. +type PlaygroundRequest struct { + Sensor string `json:"sensor"` + Horizon string `json:"horizon"` + Scenario string `json:"scenario"` + Weather *PlaygroundWeather `json:"weather,omitempty"` + IsHoliday *bool `json:"is_holiday,omitempty"` +} + +// PlaygroundResponse mirrors the subset of FastAPI POST /predict that the +// playground returns to the browser. +type PlaygroundResponse struct { + Sensor string `json:"sensor"` + Horizon string `json:"horizon"` + Scenario string `json:"scenario"` + Points []model.ForecastPoint `json:"points"` + DataVersion string `json:"data_version"` + ModelVersion string `json:"model_version"` + ContextVersion string `json:"context_version"` +} + // SimulateRequest mirrors the API contract POST /simulate. type SimulateRequest struct { Scenario string `json:"scenario"` @@ -148,6 +178,20 @@ func (c *Client) Predict(ctx context.Context, req PredictRequest) ([]model.Forec return nil, fmt.Errorf("ml: predict returned no points") } +// PlaygroundPredict calls POST /predict with optional weather and holiday +// overrides. Unlike Predict it preserves the response versions for the public +// playground. +func (c *Client) PlaygroundPredict(ctx context.Context, req PlaygroundRequest) (PlaygroundResponse, error) { + var out PlaygroundResponse + if err := c.post(ctx, "/predict", req, &out); err != nil { + return out, err + } + if len(out.Points) == 0 { + return out, fmt.Errorf("ml: playground predict returned no points") + } + return out, nil +} + // Simulate calls POST /simulate and returns forecasts keyed // sensor -> horizon -> points. func (c *Client) Simulate(ctx context.Context, req SimulateRequest) (map[string]map[string][]model.ForecastPoint, error) { diff --git a/internal/ml/client_test.go b/internal/ml/client_test.go index aeb6330..e773429 100644 --- a/internal/ml/client_test.go +++ b/internal/ml/client_test.go @@ -93,6 +93,72 @@ func TestPredictTimeout(t *testing.T) { } } +func TestPlaygroundPredictOptionalWeatherAndHoliday(t *testing.T) { + var bodies []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/predict" { + t.Errorf("path=%q", r.URL.Path) + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode request: %v", err) + } + bodies = append(bodies, body) + _, _ = w.Write([]byte(`{ + "sensor":"hn-bahnhof-01", + "horizon":"48h", + "scenario":"base", + "points":[{"t":"2026-11-16T09:00:00Z","v":12.3,"lo":8.1,"hi":17.2}], + "data_version":"d1", + "model_version":"m1", + "context_version":"c1" + }`)) + })) + defer srv.Close() + + client := New(srv.URL, time.Second) + if _, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{ + Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base", + }); err != nil { + t.Fatalf("PlaygroundPredict without weather: %v", err) + } + if len(bodies) != 1 { + t.Fatalf("requests=%d", len(bodies)) + } + if _, ok := bodies[0]["weather"]; ok { + t.Errorf("weather should be omitted when not supplied: %+v", bodies[0]) + } + if _, ok := bodies[0]["is_holiday"]; ok { + t.Errorf("is_holiday should be omitted when not supplied: %+v", bodies[0]) + } + + temp := 29.0 + holiday := true + resp, err := client.PlaygroundPredict(context.Background(), PlaygroundRequest{ + Sensor: "hn-bahnhof-01", Horizon: "48h", Scenario: "base", + Weather: &PlaygroundWeather{TempC: &temp}, IsHoliday: &holiday, + }) + if err != nil { + t.Fatalf("PlaygroundPredict with weather: %v", err) + } + if resp.ModelVersion != "m1" || resp.DataVersion != "d1" || len(resp.Points) != 1 { + t.Fatalf("response=%+v", resp) + } + if len(bodies) != 2 { + t.Fatalf("requests=%d", len(bodies)) + } + weather, ok := bodies[1]["weather"].(map[string]any) + if !ok || weather["temp_c"] != float64(29) { + t.Errorf("weather=%+v", bodies[1]["weather"]) + } + if _, ok := weather["precip_mm"]; ok { + t.Errorf("precip_mm should be omitted: %+v", weather) + } + if bodies[1]["is_holiday"] != true { + t.Errorf("is_holiday=%+v", bodies[1]["is_holiday"]) + } +} + func TestSimulate(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req SimulateRequest