|
| 1 | +/* |
| 2 | +Copyright 2026 The llm-d Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package proxy |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "fmt" |
| 23 | + "io" |
| 24 | + "net/http" |
| 25 | + "time" |
| 26 | + |
| 27 | + "go.opentelemetry.io/otel/attribute" |
| 28 | + "go.opentelemetry.io/otel/codes" |
| 29 | + "go.opentelemetry.io/otel/trace" |
| 30 | + |
| 31 | + logging "github.com/llm-d/llm-d-router/pkg/common/observability/logging" |
| 32 | + "github.com/llm-d/llm-d-router/pkg/common/observability/tracing" |
| 33 | +) |
| 34 | + |
| 35 | +// handleP2P implements the vLLM OffloadingConnector P2P orchestration contract. The |
| 36 | +// prefiller stores KV under a kv_request_id with no peer address; the decoder |
| 37 | +// pulls it using the prefiller's OffloadingConnector P2P tier host/port. Both legs are |
| 38 | +// dispatched concurrently: the connector parks any KV blocks stored before the |
| 39 | +// decoder's fetch binds the session, so ordering between the legs is safe. |
| 40 | +func (s *Server) handleP2P(w http.ResponseWriter, r *http.Request, prefillPodHostPort string) { |
| 41 | + body, err := io.ReadAll(r.Body) |
| 42 | + if err != nil { |
| 43 | + if err := errorJSONInvalid(fmt.Errorf("failed to read request body: %w", err), w); err != nil { |
| 44 | + s.logger.Error(err, "failed to send error response to client") |
| 45 | + } |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + var requestData map[string]any |
| 50 | + if err := json.Unmarshal(body, &requestData); err != nil { |
| 51 | + if err := errorJSONInvalid(err, w); err != nil { |
| 52 | + s.logger.Error(err, "failed to send error response to client") |
| 53 | + } |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + kvRequestID := newUUID() |
| 58 | + s.logger.Info("running P2P protocol", |
| 59 | + "prefill_host", extractHost(prefillPodHostPort), |
| 60 | + "kv_request_id", kvRequestID, |
| 61 | + "p2p_connector_port", s.config.P2PConnectorPort) |
| 62 | + |
| 63 | + // Prefill leg: store KV under kv_request_id, no peer address. Capped to a |
| 64 | + // single output token so the prefiller returns as soon as KV is stored. |
| 65 | + prefillData := make(map[string]any, len(requestData)+1) |
| 66 | + for k, v := range requestData { |
| 67 | + prefillData[k] = v |
| 68 | + } |
| 69 | + prefillData[requestFieldKVTransferParams] = map[string]any{ |
| 70 | + requestFieldP2PDecodeParams: map[string]any{ |
| 71 | + requestFieldKVRequestID: kvRequestID, |
| 72 | + }, |
| 73 | + } |
| 74 | + prefillData[requestFieldStream] = false |
| 75 | + delete(prefillData, requestFieldStreamOptions) |
| 76 | + prefillData[requestFieldMaxTokens] = 1 |
| 77 | + if _, ok := prefillData[requestFieldMaxCompletionTokens]; ok { |
| 78 | + prefillData[requestFieldMaxCompletionTokens] = 1 |
| 79 | + } |
| 80 | + |
| 81 | + prefillBody, err := json.Marshal(prefillData) |
| 82 | + if err != nil { |
| 83 | + if err := errorJSONInvalid(err, w); err != nil { |
| 84 | + s.logger.Error(err, "failed to send error response to client") |
| 85 | + } |
| 86 | + return |
| 87 | + } |
| 88 | + if v := s.logger.V(logging.TRACE); v.Enabled() { |
| 89 | + v.Info("prefill request body", "body", string(prefillBody)) |
| 90 | + } |
| 91 | + |
| 92 | + // Decode leg: pull KV from the prefiller's OffloadingConnector P2P tier. Original body |
| 93 | + // (streaming, token limits) is preserved. |
| 94 | + decodeData := make(map[string]any, len(requestData)+1) |
| 95 | + for k, v := range requestData { |
| 96 | + decodeData[k] = v |
| 97 | + } |
| 98 | + decodeData[requestFieldKVTransferParams] = map[string]any{ |
| 99 | + requestFieldP2PPrefillParams: map[string]any{ |
| 100 | + requestFieldKVRequestID: kvRequestID, |
| 101 | + requestFieldRemoteHost: extractHost(prefillPodHostPort), |
| 102 | + requestFieldRemotePort: s.config.P2PConnectorPort, |
| 103 | + }, |
| 104 | + } |
| 105 | + |
| 106 | + decodeBody, err := json.Marshal(decodeData) |
| 107 | + if err != nil { |
| 108 | + if err := errorJSONInvalid(err, w); err != nil { |
| 109 | + s.logger.Error(err, "failed to send error response to client") |
| 110 | + } |
| 111 | + return |
| 112 | + } |
| 113 | + if v := s.logger.V(logging.TRACE); v.Enabled() { |
| 114 | + v.Info("decode request body", "body", string(decodeBody)) |
| 115 | + } |
| 116 | + |
| 117 | + s.handleP2PConcurrentRequests(w, r, prefillBody, decodeBody, prefillPodHostPort) |
| 118 | +} |
| 119 | + |
| 120 | +func (s *Server) handleP2PConcurrentRequests(w http.ResponseWriter, r *http.Request, prefillBody, decodeBody []byte, prefillHost string) { |
| 121 | + tracer := tracing.Tracer(tracerScope) |
| 122 | + ctx := r.Context() |
| 123 | + |
| 124 | + // WithoutCancel for prefill so it isn't aborted when the decode response finishes first. |
| 125 | + prefillReq := cloneRequestWithBody(context.WithoutCancel(ctx), r, prefillBody) |
| 126 | + decodeReq := cloneRequestWithBody(ctx, r, decodeBody) |
| 127 | + |
| 128 | + // Prefill runs in a goroutine: only stores KV, response is discarded. |
| 129 | + // Decode runs on the main thread: writes the actual response back via w. |
| 130 | + ctx, prefillSpan := tracer.Start(ctx, "llm_d.pd_proxy.prefill", |
| 131 | + trace.WithSpanKind(trace.SpanKindInternal), |
| 132 | + ) |
| 133 | + prefillSpan.SetAttributes( |
| 134 | + attribute.String("llm_d.pd_proxy.prefill_target", prefillHost), |
| 135 | + attribute.String("llm_d.pd_proxy.connector", KVConnectorOffloading), |
| 136 | + attribute.Bool("llm_d.pd_proxy.prefill.async", true), |
| 137 | + ) |
| 138 | + prefillStart := time.Now() |
| 139 | + |
| 140 | + prefillHandler, err := s.prefillerProxyHandler(prefillHost) |
| 141 | + if err != nil { |
| 142 | + prefillSpan.SetStatus(codes.Error, "failed to create prefill handler") |
| 143 | + prefillSpan.End() |
| 144 | + if err := errorBadGateway(err, w); err != nil { |
| 145 | + s.logger.Error(err, "failed to send error response to client") |
| 146 | + } |
| 147 | + return |
| 148 | + } |
| 149 | + |
| 150 | + go func() { |
| 151 | + defer prefillSpan.End() |
| 152 | + defer func() { |
| 153 | + if rec := recover(); rec != nil && rec != http.ErrAbortHandler { |
| 154 | + s.logger.Error(fmt.Errorf("panic: %v", rec), "panic in prefill request") |
| 155 | + } |
| 156 | + }() |
| 157 | + pw := &bufferedResponseWriter{} |
| 158 | + prefillHandler.ServeHTTP(pw, prefillReq) |
| 159 | + prefillDuration := time.Since(prefillStart) |
| 160 | + prefillSpan.SetAttributes( |
| 161 | + attribute.Int("llm_d.pd_proxy.prefill.status_code", pw.statusCode), |
| 162 | + attribute.Float64("llm_d.pd_proxy.prefill.duration_ms", float64(prefillDuration.Milliseconds())), |
| 163 | + ) |
| 164 | + if isHTTPError(pw.statusCode) { |
| 165 | + prefillSpan.SetStatus(codes.Error, "prefill request failed") |
| 166 | + } |
| 167 | + s.logger.V(logging.DEBUG).Info("p2p prefill request completed", "status", pw.statusCode) |
| 168 | + }() |
| 169 | + |
| 170 | + // Decode Stage |
| 171 | + ctx, decodeSpan := tracer.Start(ctx, "llm_d.pd_proxy.decode", |
| 172 | + trace.WithSpanKind(trace.SpanKindInternal), |
| 173 | + ) |
| 174 | + defer decodeSpan.End() |
| 175 | + |
| 176 | + decodeSpan.SetAttributes( |
| 177 | + attribute.String("llm_d.pd_proxy.connector", KVConnectorOffloading), |
| 178 | + attribute.Bool("llm_d.pd_proxy.decode.concurrent_with_prefill", true), |
| 179 | + ) |
| 180 | + decodeStart := time.Now() |
| 181 | + |
| 182 | + decodeReq = decodeReq.WithContext(ctx) |
| 183 | + s.decoderProxy.ServeHTTP(w, decodeReq) |
| 184 | + |
| 185 | + decodeDuration := time.Since(decodeStart) |
| 186 | + decodeSpan.SetAttributes( |
| 187 | + attribute.Float64("llm_d.pd_proxy.decode.duration_ms", float64(decodeDuration.Milliseconds())), |
| 188 | + attribute.String("llm_d.pd_proxy.decode.target", s.config.DecoderURL.Host), |
| 189 | + ) |
| 190 | + |
| 191 | + // End-to-end P/D timing. True TTFT captures time from gateway request start |
| 192 | + // to decode start; prefill duration is tracked in the async prefill span. |
| 193 | + if currentSpan := trace.SpanFromContext(ctx); currentSpan.SpanContext().IsValid() { |
| 194 | + var totalDuration time.Duration |
| 195 | + var trueTTFT time.Duration |
| 196 | + if requestStartValue := ctx.Value(requestStartTimeKey); requestStartValue != nil { |
| 197 | + if requestStart, ok := requestStartValue.(time.Time); ok { |
| 198 | + totalDuration = time.Since(requestStart) |
| 199 | + trueTTFT = decodeStart.Sub(requestStart) |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + currentSpan.SetAttributes( |
| 204 | + attribute.Float64("llm_d.pd_proxy.total_duration_ms", float64(totalDuration.Milliseconds())), |
| 205 | + attribute.Float64("llm_d.pd_proxy.true_ttft_ms", float64(trueTTFT.Milliseconds())), |
| 206 | + attribute.Float64("llm_d.pd_proxy.decode_duration_ms", float64(decodeDuration.Milliseconds())), |
| 207 | + attribute.Bool("llm_d.pd_proxy.concurrent_pd", true), |
| 208 | + ) |
| 209 | + } |
| 210 | +} |
0 commit comments