before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
select { case <-ctx.Done(): return ctx.Err() default: } req, err := srv.Recv() if err == io.EOF { return nil } if err != nil { return status.Errorf(codes.Unknown, "cannot receive stream request: %v", err) } resp := &extProcPb.ProcessingResponse{} switch v := req.Request.(type) { case...
in the configuration in `config/gateway/gateway.yaml` we still use buffer for request, is this still consistent?
ctx := srv.Context() requestID := uuid.New().String() for { select { case <-ctx.Done(): return ctx.Err() default: } req, err := srv.Recv() if err == io.EOF { return nil } if err != nil { return status.Errorf(codes.Unknown, "cannot receive stream request: %v", err) } resp := &extProcPb...
@@ -120,13 +124,13 @@ func (s *Server) Process(srv extProcPb.ExternalProcessor_ProcessServer) error { resp, user, rpm, routingStrategy = s.HandleRequestHeaders(ctx, requestID, req) case *extProcPb.ProcessingRequest_RequestBody: - resp, targetPodIP = s.HandleRequestBody(ctx, requestID, req, user, routingStrat...
pkg/plugins/gateway/gateway.go
26
Go
0.571
question
113
51
51
false
Add envoy gateway streaming support
377
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
}}}, err.Error()) } defer func() { go func() { s.cache.AddRequestTrace(res.Model, res.Usage.PromptTokens, res.Usage.CompletionTokens) }() }() headers := []*configPb.HeaderValueOption{} if user.Name != "" { tpm, err := s.ratelimiter.Incr(ctx, fmt.Sprintf("%v_TPM_CURRENT", user), int64(res.Usage.Tot...
seems it's binary logic, why not just use if..else..
return &extProcPb.ProcessingResponse{ Response: &extProcPb.ProcessingResponse_ResponseHeaders{ ResponseHeaders: &extProcPb.HeadersResponse{ Response: &extProcPb.CommonResponse{ HeaderMutation: &extProcPb.HeaderMutation{ SetHeaders: headers, }, ClearRouteCache: true, }, }, }, } ...
@@ -311,64 +337,97 @@ func (s *Server) HandleResponseHeaders(ctx context.Context, requestID string, re } } -func (s *Server) HandleResponseBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User, rpm int64, targetPodIP string) *extProcPb.ProcessingResponse { - klog.Infof("--- ...
pkg/plugins/gateway/gateway.go
26
Go
0.286
suggestion
52
51
51
false
Add envoy gateway streaming support
377
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
Key: "target-pod", RawValue: []byte(targetPodIP), }, }, ) } return &extProcPb.ProcessingResponse{ Response: &extProcPb.ProcessingResponse_ResponseBody{ ResponseBody: &extProcPb.BodyResponse{ Response: &extProcPb.CommonResponse{ HeaderMutation: &extProcPb.HeaderMutation{ Se...
nit: in future, we can add some post-processor interface here. I think update rate limit would be one of them. This makes the code cleaner.
Key: "x-streaming-error", RawValue: []byte("true"), }}}, err.Error()) } case false: if err := json.Unmarshal(b.ResponseBody.Body, &res); err != nil { klog.ErrorS(err, "error to unmarshal response", "requestID", requestID, "responseBody", string(b.ResponseBody.GetBody())) return generateErrorResp...
@@ -311,64 +337,97 @@ func (s *Server) HandleResponseHeaders(ctx context.Context, requestID string, re } } -func (s *Server) HandleResponseBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User, rpm int64, targetPodIP string) *extProcPb.ProcessingResponse { - klog.Infof("--- ...
pkg/plugins/gateway/gateway.go
26
Go
0.357
nitpick
139
51
51
false
Add envoy gateway streaming support
377
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
var ok bool var jsonMap map[string]interface{} body := req.Request.(*extProcPb.ProcessingRequest_RequestBody) if err := json.Unmarshal(body.RequestBody.GetBody(), &jsonMap); err != nil { return generateErrorResponse(envoyTypePb.StatusCode_InternalServerError, []*configPb.HeaderValueOption{{Header: &configPb.H...
Here, it requires user to specify a header for stream usage `x-stream-options`? can it be compatible with openai stream sdk? does openai-sdk automatically register this header?
func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User, routingStrategy string) (*extProcPb.ProcessingResponse, string, bool) { klog.InfoS("-- In RequestBody processing ...", "requestID", requestID) var model, targetPodIP string var ok, stream boo...
@@ -203,25 +207,46 @@ func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req }, user, rpm, routingStrategy } -func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, user utils.User, routingStrategy string) (*extProcPb.ProcessingResponse...
pkg/plugins/gateway/gateway.go
26
Go
0.571
question
177
51
51
false
Add envoy gateway streaming support
377
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
*/ package common // ScalingContext defines the generalized common that holds all necessary data for scaling calculations. type ScalingContext interface { GetTargetValue() float64 GetUpFluctuationTolerance() float64 GetDownFluctuationTolerance() float64 GetMaxScaleUpRate() float64 GetMaxScaleDownRate() float64 ...
What does `UpdateByPaTypes` mean? it tries to build the context from the object?
*/ package common import ( "strconv" autoscalingv1alpha1 "github.com/aibrix/aibrix/api/autoscaling/v1alpha1" "k8s.io/klog/v2" ) const ( AutoscalingLabelPrefix = "autoscaling.aibrix.ai/" maxScaleUpRateLabel = AutoscalingLabelPrefix + "max-scale-up-rate" maxScaleDownRateLabel = AutoscalingLabelPrefix + "max...
@@ -24,6 +37,7 @@ type ScalingContext interface { GetMaxScaleUpRate() float64 GetMaxScaleDownRate() float64 GetCurrentUsePerPod() float64 + UpdateByPaTypes(pa *autoscalingv1alpha1.PodAutoscaler) error
pkg/controller/podautoscaler/common/context.go
26
Go
0.5
question
80
51
51
false
Enable setting PodAutoscaler configuration via YAML labels
409
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
time.sleep(wait_time) next_start += interval_sec end_time = time.time() logging.info(f"Benchmark completed in {end_time - start_time:.2f} seconds") else: try: interval_sec = args.w_interval_sec with open(args.workload, 'r') as file:...
minor: Let's use logging for consistency
if wait_time > 0: time.sleep(wait_time) next_start += interval_sec end_time = time.time() logging.info(f"Benchmark completed in {end_time - start_time:.2f} seconds") if __name__ == "__main__": parser = FlexibleArgumentParser(description='Benchmark the performance of...
@@ -235,69 +235,96 @@ def sample_sharegpt_requests( def main(args): + FROM_GENERATOR = args.workload is not None WORKLOAD_MODE = args.concurrency is not None tokenizer = get_tokenizer(args.model, trust_remote_code=True) - if args.dataset_path is not None: - logging.info(f"Start to sample {ar...
benchmarks/autoscaling/benchmark.py
26
Python
0.143
suggestion
40
51
43
false
AIBrix Workload Generator / Scenario Simulator
428
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
else: prompt_len = len(tokenizer(PROMPT).input_ids) input_requests = [(PROMPT, prompt_len, args.output_len, None)] * args.num_prompts logging.info(f"Samples results: {input_requests[0]}") start_time = time.time() if WORKLOAD_MODE: logging.info...
the client side code is exact same as generator mode. Should we refactor this part? either accept generated trace or leverage `generate_workload` to generate the load, then starts the benchmarking.
logging.info(f"Samples results: {input_requests[0]}") openai_endpoints = build_openai_endpoints(args.deployment_endpoints) openai_clients = build_openai_clients(openai_endpoints) start_time = time.time() if WORKLOAD_MODE: logging.info(f"Starting benchmark for {args.num_prompts} prompts wit...
@@ -235,69 +235,96 @@ def sample_sharegpt_requests( def main(args): + FROM_GENERATOR = args.workload is not None WORKLOAD_MODE = args.concurrency is not None tokenizer = get_tokenizer(args.model, trust_remote_code=True) - if args.dataset_path is not None: - logging.info(f"Start to sample {ar...
benchmarks/autoscaling/benchmark.py
26
Python
0.643
refactor
202
51
51
false
AIBrix Workload Generator / Scenario Simulator
428
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
prompt = dataset[i][0] prompt_token_ids = tokenizer(prompt).input_ids completion = dataset[i][1] completion_token_ids = tokenizer(completion).input_ids prompt_len = len(prompt_token_ids) output_len = len(completion_token_ids) if fixed_output_len is None else fixed_output_...
lot of clients/experiments has this similar methods. can we refactor this part? If you do not like to make it now, let's have a brief chat.
prompt_token_ids = tokenizer(prompt).input_ids completion = dataset[i][1] completion_token_ids = tokenizer(completion).input_ids prompt_len = len(prompt_token_ids) output_len = len(completion_token_ids) if fixed_output_len is None else fixed_output_len if prompt_len < 4 o...
@@ -219,36 +220,61 @@ def main(args): if args.num_prompts < len(openai_endpoints) * args.concurrency: num_prompts = len(openai_endpoints) * args.concurrency - if args.dataset_path is not None: - logging.info(f"Start to sample {num_prompts} prompts from {args.dataset_path}") - input_requ...
benchmarks/lora/benchmark.py
26
Python
0.429
refactor
140
51
51
false
AIBrix Workload Generator / Scenario Simulator
428
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
) const ( metricServerDefaultMetricWindow = time.Minute ) type KPAMetricsClient struct { fetcher MetricFetcher // collectionsMutex protects access to both panicWindowDict and stableWindowDict, // ensuring thread-safe read and write operations. It uses a read-write mutex to // allow multiple concurrent reads whi...
client is not singleton now? it only response for one metric?
const ( metricServerDefaultMetricWindow = time.Minute paGranularity = time.Second ) type KPAMetricsClient struct { fetcher MetricFetcher // collectionsMutex protects access to both panicWindowDict and stableWindowDict, // ensuring thread-safe read and write operations. It uses a read-write mut...
@@ -54,42 +54,28 @@ type KPAMetricsClient struct { // are collected and processed within the sliding window. granularity time.Duration // the difference between stable and panic metrics is the time window range - panicWindowDict map[NamespaceNameMetric]*aggregation.TimeWindow - stableWindowDict map[NamespaceName...
pkg/controller/podautoscaler/metrics/client.go
26
Go
0.214
question
61
51
51
false
Refactor Scaler: Resolve Issues with Metric Parameter Updates in Multiple KPAs
437
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
func (c *KPAMetricsClient) UpdateMetricIntoWindow(metricKey NamespaceNameMetric, now time.Time, metricValue float64) error { // Add to panic and stable windows; create a new window if not present in the map // Ensure that panicWindowDict and stableWindowDict maps are checked and updated updateWindow := func(windowDi...
how does it know the metrics now?
func (c *KPAMetricsClient) UpdateMetricIntoWindow(now time.Time, metricValue float64) error { c.panicWindow.Record(now, metricValue) c.stableWindow.Record(now, metricValue) return nil } func (c *KPAMetricsClient) UpdatePodListMetric(metricValues []float64, metricKey NamespaceNameMetric, now time.Time) error { retu...
@@ -112,7 +98,7 @@ func (c *KPAMetricsClient) UpdateMetrics(now time.Time, metricKey NamespaceNameM defer c.collectionsMutex.Unlock() // Update metrics into the window for tracking - err := c.UpdateMetricIntoWindow(metricKey, now, sumMetricValue) + err := c.UpdateMetricIntoWindow(now, sumMetricValue)
pkg/controller/podautoscaler/metrics/client.go
26
Go
0.071
question
34
51
51
false
Refactor Scaler: Resolve Issues with Metric Parameter Updates in Multiple KPAs
437
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
var ( DefaultRequeueDuration = 10 * time.Second ) // Add creates a new PodAutoscaler Controller and adds it to the Manager with default RBAC. // The Manager will set fields on the Controller and Start it when the Manager is Started. func Add(mgr manager.Manager) error { r, err := newReconciler(mgr) if err != nil {...
em. in this case, does it mean multiple HPA, KPA or APA scalers are flatten? We used to have 3 singleton autoscaler
var ( DefaultRequeueDuration = 10 * time.Second ) // Add creates a new PodAutoscaler Controller and adds it to the Manager with default RBAC. // The Manager will set fields on the Controller and Start it when the Manager is Started. func Add(mgr manager.Manager) error { r, err := newReconciler(mgr) if err != nil {...
@@ -74,36 +74,9 @@ func newReconciler(mgr manager.Manager) (reconcile.Reconciler, error) { Mapper: mgr.GetRESTMapper(), resyncInterval: 10 * time.Second, // TODO: this should be override by an environment variable eventCh: make(chan event.GenericEvent), + AutoscalerMap: make(map[metrics.Namesp...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.429
suggestion
118
51
51
false
Refactor Scaler: Resolve Issues with Metric Parameter Updates in Multiple KPAs
437
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
}, { "name": "gpu_cache_usage_perc", "type": "gauge", "description": "GPU KV-cache usage. 1 means 100 percent usage.", "value": overrides.get( "gpu_cache_usage_perc", gpu_cache_usage_perc ) }, ] # Generate all m...
I forgot to share with you the lora metrics as well. Do you need any help here?
"description": "Average prefill throughput in tokens/s.", "value": overrides.get("avg_prompt_throughput", avg_prompt_throughput) }, { "name": "avg_generation_throughput_toks_per_s", "type": "gauge", "description": "Average generation throughput...
@@ -386,17 +394,12 @@ def metrics(): ] # Generate all metrics - metrics_output = "".join( - generate_counter_gauge_metric(metric["name"], metric["type"], metric["description"], model_name, - metric["value"]) - for metric in simple_metrics - ) - - l...
docs/development/app/app.py
26
Python
0.214
question
79
51
51
false
Support metrics multi labels for different models
450
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
}, { "name": "avg_generation_throughput_toks_per_s", "type": "gauge", "description": "Average generation throughput in tokens/s.", "value": overrides.get("avg_generation_throughput", avg_generation_throughput) }, { "name": "gpu_...
I think this is due to my careless. `lora-model-1` was for testing but not real production workloads, we should correct it here later
"description": "Number of requests waiting to be processed.", "value": overrides.get("waiting", waiting) }, { "name": "avg_prompt_throughput_toks_per_s", "type": "gauge", "description": "Average prefill throughput in tokens/s.", "va...
@@ -386,17 +394,12 @@ def metrics(): ] # Generate all metrics - metrics_output = "".join( - generate_counter_gauge_metric(metric["name"], metric["type"], metric["description"], model_name, - metric["value"]) - for metric in simple_metrics - ) - - l...
docs/development/app/app.py
26
Python
0.571
suggestion
133
51
51
false
Support metrics multi labels for different models
450
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
"k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" modelv1alpha1 "github.com/aibrix/aibrix/api/model/v1alpha1" v1alpha1 "github.com/aibrix/aibrix/pkg/client/clientset/versioned" v1alpha1scheme "github.com/aibrix/aibrix/pkg/client/clientset/versioned/scheme" "github.com/aibrix/aibrix/pkg/met...
Seems `PodModelMetrics` can not be replaced by `PodMetrics` and `ModelToPodMapping` together. right? we need another dimension or hierarchy to support lora case
"k8s.io/client-go/tools/cache" "k8s.io/klog/v2" modelv1alpha1 "github.com/aibrix/aibrix/api/model/v1alpha1" v1alpha1 "github.com/aibrix/aibrix/pkg/client/clientset/versioned" v1alpha1scheme "github.com/aibrix/aibrix/pkg/client/clientset/versioned/scheme" "github.com/aibrix/aibrix/pkg/metrics" prometheusv1 "gith...
@@ -61,10 +61,11 @@ type Cache struct { metrics map[string]interface{} ModelMetrics map[string]map[string]interface{} Pods map[string]*v1.Pod - PodMetrics map[string]map[string]metrics.MetricValue // pod_name: map[metric_name]metric_val - PodToModelMapping map[string]map[string]...
pkg/cache/cache.go
26
Go
0.571
suggestion
160
51
51
false
Support metrics multi labels for different models
450
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
continue } value := metricValue.GetHistogramValue() c.PodMetrics[pod.Name][metricName] = &metrics.HistogramMetricValue{ Sum: value.Sum, Count: value.Count, Buckets: value.Buckets, } klog.V(5).InfoS("Successfully parsed metrics", "metric", metricName, "PodIP", pod.Status.PodIP, "Por...
using `expfmt` makes a lot of sense. Great
continue } podName := pod.Name if len(c.PodMetrics[podName]) == 0 { c.PodMetrics[podName] = map[string]metrics.MetricValue{} } if len(c.PodModelMetrics[podName]) == 0 { c.PodModelMetrics[podName] = make(map[string]map[string]metrics.MetricValue) } // We should use the primary container port. In ...
@@ -538,41 +587,83 @@ func (c *Cache) updatePodMetrics() { } }() - body, err := io.ReadAll(resp.Body) + // TODO: the metrics should come from those router subscribers in future + var parser expfmt.TextParser
pkg/cache/cache.go
26
Go
0.214
suggestion
42
51
51
false
Support metrics multi labels for different models
450
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
continue } histogramValue := &metrics.HistogramMetricValue{ Sum: metricValue.Sum, Count: metricValue.Count, Buckets: metricValue.Buckets, } err = c.updatePodRecord(podName, modelName, metricName, scope, histogramValue) if err != nil { klog.Errorf("Failed to update met...
Technically, this might not be populated if pod just arrive. but I think this is ok, we may miss few metrics until the pod is added into the map.
continue } histogramValue := &metrics.HistogramMetricValue{ Sum: metricValue.Sum, Count: metricValue.Count, Buckets: metricValue.Buckets, } err = c.updatePodRecord(podName, modelName, metricName, scope, histogramValue) if err != nil { klog.Errorf("Failed to update met...
@@ -672,39 +672,43 @@ func (c *Cache) updatePodMetrics() { } for _, metricName := range prometheusMetricNames { - // TODO: Get another model PromQL value from the same pod - modelName := pod.Labels["model.aibrix.ai/name"] - queryLabels := map[string]string{ - "model_name": modelName, - "instance": ...
pkg/cache/cache.go
26
Go
0.357
suggestion
146
51
51
false
Fix multi models metric result in PromQL
458
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
initial_err_perc = 0.5, err_step = 0.05 ) if sampled_requests: # Only add non-empty groups grouped_requests.append((ts, sampled_requests)) ts += interval_ms if ts > duration_ms: break # Move to the next tim...
I suggest to have all `--trace-type` listed here.
sampled_requests = sample_sharegpt_requests_len_range( df = sharegpt_df, num_requests = len(input_lens), input_lens = input_lens, output_lens = output_lens, initial_err_perc = 0.5, err_step = 0.05 ) ...
@@ -180,64 +180,64 @@ def generate_from_azure_csv(file_path: str, ) if sampled_requests: # Only add non-empty groups - grouped_requests.append(sampled_requests) - + grouped_requests.append((ts, sampled_requests)) + ts += interval_ms + if t...
benchmarks/generator/workload_generator.py
26
Python
0.357
suggestion
49
51
51
false
Refactor generator to generate time-based traces
478
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
err_step = 0.05 ) if sampled_requests: # Only add non-empty groups grouped_requests.append((ts, sampled_requests)) ts += interval_ms if ts > duration_ms: break # Move to the next time range current_time += time_ran...
Let's add more details in the `help`. what kind of trace-type needs such file etc.
df = sharegpt_df, num_requests = len(input_lens), input_lens = input_lens, output_lens = output_lens, initial_err_perc = 0.5, err_step = 0.05 ) if sampled_requests: # Only add non-empty gro...
@@ -180,64 +180,64 @@ def generate_from_azure_csv(file_path: str, ) if sampled_requests: # Only add non-empty groups - grouped_requests.append(sampled_requests) - + grouped_requests.append((ts, sampled_requests)) + ts += interval_ms + if t...
benchmarks/generator/workload_generator.py
26
Python
0.5
suggestion
84
51
51
false
Refactor generator to generate time-based traces
478
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
) if sampled_requests: # Only add non-empty groups grouped_requests.append((ts, sampled_requests)) ts += interval_ms if ts > duration_ms: break # Move to the next time range current_time += time_range # Print or process group...
let's change the default one to something else. like https://huggingface.co/Qwen/Qwen2.5-Coder-7B-Instruct. llama7b can not be publicly accessible
num_requests = len(input_lens), input_lens = input_lens, output_lens = output_lens, initial_err_perc = 0.5, err_step = 0.05 ) if sampled_requests: # Only add non-empty groups grouped_requests.a...
@@ -180,64 +180,64 @@ def generate_from_azure_csv(file_path: str, ) if sampled_requests: # Only add non-empty groups - grouped_requests.append(sampled_requests) - + grouped_requests.append((ts, sampled_requests)) + ts += interval_ms + if t...
benchmarks/generator/workload_generator.py
26
Python
0.429
suggestion
146
51
51
false
Refactor generator to generate time-based traces
478
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
current_time += time_range # Print or process grouped_requests as needed # Save to file grouped_requests = make_serializable(grouped_requests) save_workload(grouped_requests, output_file) return grouped_requests if __name__ == '__main__': parser = argparse.ArgumentParser(desc...
suggest to use `second` as the time unit. for duration, normally, we at least generate 120-600 etc. won't be any case less than 1s
grouped_requests.append((ts, sampled_requests)) ts += interval_ms if ts > duration_ms: break # Move to the next time range current_time += time_range # Print or process grouped_requests as needed # Save to file grouped_requests = make_serializable(gro...
@@ -180,64 +180,64 @@ def generate_from_azure_csv(file_path: str, ) if sampled_requests: # Only add non-empty groups - grouped_requests.append(sampled_requests) - + grouped_requests.append((ts, sampled_requests)) + ts += interval_ms + if t...
benchmarks/generator/workload_generator.py
26
Python
0.571
suggestion
130
51
51
false
Refactor generator to generate time-based traces
478
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
*/ package metrics const ( NumRequestsRunning = "num_requests_running" NumRequestsWaiting = "num_requests_waiting" NumRequestsSwapped = "num_requests_swapped" AvgPromptThroughputToksPerS = "avg_prompt_throughput_toks_per_s" AvgGenerationThroughputTok...
the default metric name is `gpu_cache_usage_perc`. without `_pod`. should we make it aligned?
*/ package metrics const ( NumRequestsRunning = "num_requests_running" NumRequestsWaiting = "num_requests_waiting" NumRequestsSwapped = "num_requests_swapped" AvgPromptThroughputToksPerS = "avg_prompt_throughput_toks_per_s" AvgGenerationThroughputTok...
@@ -17,20 +17,32 @@ limitations under the License. package metrics const ( - NumRequestsRunning = "num_requests_running" - NumRequestsWaiting = "num_requests_waiting" - NumRequestsSwapped = "num_requests_swapped" - AvgPromptThroughputToksPerS = "avg_prompt_throughput_toks_...
pkg/metrics/metrics.go
26
Go
0.429
performance
93
51
51
false
Add metrics that scheduling needed
486
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
return 0, "", currentTimestamp, fmt.Errorf("can not calculate metrics for scale %s", pa.Spec.ScaleTargetRef.Name) } // refer to knative-serving. // In pkg/reconciler/autoscaling/kpa/kpa.go:198, kpa maintains a list of deciders into multi-scaler, each of them corresponds to a pa (PodAutoscaler). // We create or updat...
the indent doesn't look correct?
// In pkg/reconciler/autoscaling/kpa/kpa.go:198, kpa maintains a list of deciders into multi-scaler, each of them corresponds to a pa (PodAutoscaler). // We create or update the scaler instance according to the pa passed in func (r *PodAutoscalerReconciler) updateScalerSpec(ctx context.Context, pa autoscalingv1alpha1.P...
@@ -616,7 +627,7 @@ func (r *PodAutoscalerReconciler) updateScalerSpec(ctx context.Context, pa autos func (r *PodAutoscalerReconciler) updateMetricsForScale(ctx context.Context, pa autoscalingv1alpha1.PodAutoscaler, scale *unstructured.Unstructured) (err error) { currentTimestamp := time.Now() - metricKey := NewNa...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.071
question
32
51
51
false
[Bug] handle metricKey creation with MetricsSources
488
vllm-project/aibrix
2,572
Go
Jeffwan
nwangfw
logger.V(4).Info("Obtained selector and get ReadyPodsCount", "selector", labelsSelector, "originalReadyPodsCount", originalReadyPodsCount) var metricKey metrics.NamespaceNameMetric if len(pa.Spec.MetricsSources) > 0 { metricKey = metrics.NewNamespaceNameMetric(pa.Namespace, pa.Spec.ScaleTargetRef.Name, pa.Spec.Me...
for such issues, please raise the concern. here it just use the 1st one. Is it possible to have multiple keys? just like HPA does, in that case, this will fail.
} logger.V(4).Info("Obtained selector and get ReadyPodsCount", "selector", labelsSelector, "originalReadyPodsCount", originalReadyPodsCount) // Calculate the desired number of pods using the autoscaler logic. autoScaler, ok := r.AutoscalerMap[metricKey] if !ok { return 0, "", currentTimestamp, fmt.Errorf("unsu...
@@ -602,11 +602,18 @@ func (r *PodAutoscalerReconciler) computeReplicasForMetrics(ctx context.Context, return 0, "", currentTimestamp, fmt.Errorf("can not calculate metrics for scale %s", pa.Spec.ScaleTargetRef.Name) } +func createMetricKey(pa autoscalingv1alpha1.PodAutoscaler) metrics.NamespaceNameMetric { + i...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.429
bug
162
51
51
false
[Bug] handle metricKey creation with MetricsSources
488
vllm-project/aibrix
2,572
Go
Jeffwan
nwangfw
var metricKey metrics.NamespaceNameMetric if len(pa.Spec.MetricsSources) > 0 { metricKey = metrics.NewNamespaceNameMetric(pa.Namespace, pa.Spec.ScaleTargetRef.Name, pa.Spec.MetricsSources[0].Name) } else { metricKey = metrics.NewNamespaceNameMetric(pa.Namespace, pa.Spec.ScaleTargetRef.Name, pa.Spec.TargetMetric)...
why don't you update this method but creating a new one?
logger.V(4).Info("Obtained selector and get ReadyPodsCount", "selector", labelsSelector, "originalReadyPodsCount", originalReadyPodsCount) // Calculate the desired number of pods using the autoscaler logic. autoScaler, ok := r.AutoscalerMap[metricKey] if !ok { return 0, "", currentTimestamp, fmt.Errorf("unsuppor...
@@ -602,11 +602,18 @@ func (r *PodAutoscalerReconciler) computeReplicasForMetrics(ctx context.Context, return 0, "", currentTimestamp, fmt.Errorf("can not calculate metrics for scale %s", pa.Spec.ScaleTargetRef.Name) } +func createMetricKey(pa autoscalingv1alpha1.PodAutoscaler) metrics.NamespaceNameMetric { + i...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.214
question
56
51
51
false
[Bug] handle metricKey creation with MetricsSources
488
vllm-project/aibrix
2,572
Go
Jeffwan
nwangfw
See the License for the specific language governing permissions and limitations under the License. */ package metrics import ( "context" "time" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" autoscalingv1alpha1 "github.com/aibrix/aibrix/api/autoscaling/v1alpha1" ) // NamespaceNameMetric contains the...
minor: we should leave a comment here like a TODO to remind user this is due to a limitation etc.
See the License for the specific language governing permissions and limitations under the License. */ package metrics import ( "context" "time" "k8s.io/apimachinery/pkg/types" v1 "k8s.io/api/core/v1" autoscalingv1alpha1 "github.com/aibrix/aibrix/api/autoscaling/v1alpha1" ) // NamespaceNameMetric contains the...
@@ -33,8 +33,19 @@ type NamespaceNameMetric struct { MetricName string } -func NewNamespaceNameMetric(namespace string, name string, metricName string) NamespaceNameMetric { - return NamespaceNameMetric{NamespacedName: types.NamespacedName{Namespace: namespace, Name: name}, MetricName: metricName} +func NewNamespa...
pkg/controller/podautoscaler/metrics/interface.go
26
Go
0.286
nitpick
98
51
51
false
[Bug] handle metricKey creation with MetricsSources
488
vllm-project/aibrix
2,572
Go
Jeffwan
nwangfw
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
are we sure that s3 based tos downloader will always perform better tos native one? If not, can we keep this code for a while? let's say we have tosv1 and tosv1 downloader co-exist a while. Once we are sure that v2 works better, we can deprecated v1
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
@@ -1,171 +0,0 @@ -# Copyright 2024 The Aibrix Team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable ...
python/aibrix/aibrix/downloader/tos.py
14
Python
0.5
question
249
39
39
false
[perf] Refact tos downloader in Runtime
510
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
aws_secret_access_key: "SK****",, } """ pass @lru_cache() def _is_directory(self) -> bool: """Check if model_uri is a directory.""" if self.bucket_path.endswith("/"): return True objects_out = self.client.list_objects_v2( ...
I can not remember the details here. `file.endswith("/")` means folder. here, it tries to filter all directories but left all files? but the method name is `_directory_list`?
aws_secret_access_key: "SK****",, } """ pass @lru_cache() def _is_directory(self) -> bool: """Check if model_uri is a directory.""" if self.bucket_path.endswith("/"): return True objects_out = self.client.list_objects_v2( ...
@@ -123,7 +121,9 @@ def _directory_list(self, path: str) -> List[str]: Bucket=self.bucket_name, Delimiter="/", Prefix=path ) contents = objects_out.get("Contents", []) - return [content.get("Key") for content in contents] + files = [content.get("Key") for content in contents...
python/aibrix/aibrix/downloader/s3.py
26
Python
0.5
question
175
51
51
false
[perf] Refact tos downloader in Runtime
510
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
), "S3 bucket name is not set." assert ( self.bucket_path is not None and self.bucket_path != "" ), "S3 bucket path is not set." try: self.client.head_bucket(Bucket=self.bucket_name) except Exception as e: assert False, f"S3 bucket {self.bucket...
BTW, can we keep the tos file and move TOSDownloader to tos.py?
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
@@ -182,3 +182,86 @@ def download_progress(bytes_transferred): Callback=download_progress if self.enable_progress_bar else None, ) save_meta_data(meta_data_file, etag) + + +class S3Downloader(S3BaseDownloader): + def __init__( + self, + model_uri, + mod...
python/aibrix/aibrix/downloader/s3.py
26
Python
0.286
question
63
51
230
false
[perf] Refact tos downloader in Runtime
510
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
/* Copyright 2024 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar...
Let's still use `GetPaMetricSources`? limitation could be documented. No need to expose the implemnetation in the function method names
// +kubebuilder:object:root=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // PodAutoscalerList contains a list of PodAutoscaler type PodAutoscalerList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []PodAutoscaler `json:"items"` }...
@@ -142,3 +164,11 @@ const ( // QPS is the requests per second reaching the Pod. QPS = "qps" ) + +// GetFirstPaMetricSources Currently, we don't support metric resources that are more than one yet. +func GetFirstPaMetricSources(pa PodAutoscaler) (MetricSource, error) {
api/autoscaling/v1alpha1/podautoscaler_types.go
26
Go
0.571
suggestion
135
145
32
false
Refactor metric source for customized protocol, port and path
511
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
// APA represents the AiBrix Pod Autoscaling Algorithm APA ScalingStrategyType = "APA" ) // MetricSource defines an endpoint and path from which metrics are collected. type MetricSource struct { // e.g. service1.example.com Endpoint string `json:"endpoint"` // e.g. /api/metrics/cpu Path string `json:"path"` // ...
we discussed the Endpoint here. Should we build the endpoint from Host:Port/Path or keep using it ? I kind of forgot the discussion conclusion
) type MetricSourceType string const ( // POD need to scan all k8s pods to fetch the data POD MetricSourceType = "pod" // DOMAIN only need to access specified domain DOMAIN MetricSourceType = "domain" ) type ProtocolType string const ( HTTP ProtocolType = "http" HTTPS ProtocolType = "https" ) // MetricSourc...
@@ -86,14 +84,38 @@ const ( APA ScalingStrategyType = "APA" ) +type MetricSourceType string + +const ( + // POD need to scan all k8s pods to fetch the data + POD MetricSourceType = "pod" + // DOMAIN only need to access specified domain + DOMAIN MetricSourceType = "domain" +) + +type ProtocolType string + +const ( ...
api/autoscaling/v1alpha1/podautoscaler_types.go
26
Go
0.429
suggestion
142
51
51
false
Refactor metric source for customized protocol, port and path
511
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
// Implement a timeout for the reconciliation process. ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() klog.V(4).InfoS("Reconciling PodAutoscaler", "obj", req.NamespacedName) var pa autoscalingv1alpha1.PodAutoscaler if err := r.Get(ctx, req.NamespacedName, &pa); err != nil { if errors.I...
there's some other cases like other objects sometimes get enqueued (not PodAutoscaler object), in this case, `deleteScaler` need to handle such case.
} } //+kubebuilder:rbac:groups=autoscaling.aibrix.ai,resources=podautoscalers,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=autoscaling.aibrix.ai,resources=podautoscalers/status,verbs=get;update;patch //+kubebuilder:rbac:groups=autoscaling.aibrix.ai,resources=podautoscalers/finalizers,ver...
@@ -146,8 +162,9 @@ func (r *PodAutoscalerReconciler) Reconcile(ctx context.Context, req ctrl.Reques var pa autoscalingv1alpha1.PodAutoscaler if err := r.Get(ctx, req.NamespacedName, &pa); err != nil { if errors.IsNotFound(err) { - // Object might have been deleted after reconcile request, ignore and return. -...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.643
suggestion
149
51
51
false
clean memory scaler object when pa crd is deleted
520
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
type MetricType string const ( ResourceMetrics MetricType = "resource" CustomMetrics MetricType = "custom" RawMetrics MetricType = "raw" ) // MetricFetcher defines an interface for fetching metrics. it could be Kubernetes metrics or Pod prometheus metrics. type MetricFetcher interface { // Obseleted: Call ...
this is acceptable at this moment, we could consider RestMetricsFetcher interface later to better support testing
type MetricType string const ( ResourceMetrics MetricType = "resource" CustomMetrics MetricType = "custom" RawMetrics MetricType = "raw" ) // MetricFetcher defines an interface for fetching metrics. it could be Kubernetes metrics or Pod prometheus metrics. type MetricFetcher interface { // Obseleted: Call ...
@@ -59,7 +59,10 @@ func (f *abstractMetricsFetcher) FetchMetric(ctx context.Context, pod v1.Pod, me } // RestMetricsFetcher implements MetricFetcher to fetch metrics from Pod's /metrics endpoint. -type RestMetricsFetcher struct{} +type RestMetricsFetcher struct { + // For unit test purpose only + test_url_setter fu...
pkg/controller/podautoscaler/metrics/fetcher.go
26
Go
0.429
suggestion
113
51
51
false
[Bug] Accumulated bug fix on controller manager, mock app configuration, and gpu optimizer.
522
vllm-project/aibrix
2,572
Go
Jeffwan
zhangjyr
} return podList, nil } func CountReadyPods(podList *v1.PodList) (int64, error) { if podList == nil || len(podList.Items) == 0 { return 0, nil } readyPodCount := 0 for _, pod := range podList.Items { isReady := IsPodReady(&pod) if pod.Status.Phase == v1.PodRunning && isReady { readyPodCount++ } klo...
is this method being used by other files? like some other controllers other than cache.go? I am a little bit concerned on the impact if we have other scenarios. the key difference of this change is `terminated` pod?
} return podList, nil } func CountReadyPods(podList *v1.PodList) (int64, error) { if podList == nil || len(podList.Items) == 0 { return 0, nil } readyPodCount := 0 for _, pod := range podList.Items { isReady := IsPodReady(&pod) if pod.Status.Phase == v1.PodRunning && isReady { readyPodCount++ } klo...
@@ -144,9 +144,12 @@ func CountReadyPods(podList *v1.PodList) (int64, error) { func FilterReadyPods(pods map[string]*v1.Pod) []*v1.Pod { var readyPods []*v1.Pod for _, pod := range pods { - if pod.Status.PodIP != "" && IsPodReady(pod) {
pkg/utils/pod.go
26
Go
0.643
performance
221
32
35
false
Handle terminating pod for request routing
549
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
klog.ErrorS(err, "error to unmarshal response", "requestID", requestID, "requestBody", string(body.RequestBody.GetBody())) return generateErrorResponse(envoyTypePb.StatusCode_InternalServerError, []*configPb.HeaderValueOption{{Header: &configPb.HeaderValue{ Key: "x-request-body-processing-error", RawValue: [...
it filters the terminated pods here?
klog.ErrorS(err, "error to unmarshal response", "requestID", requestID, "requestBody", string(body.RequestBody.GetBody())) return generateErrorResponse(envoyTypePb.StatusCode_InternalServerError, []*configPb.HeaderValueOption{{Header: &configPb.HeaderValue{ Key: "x-request-body-processing-error", RawValue: [...
@@ -243,6 +243,15 @@ func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *e fmt.Sprintf("model %s does not exist", model)), targetPodIP, stream } + // early reject if no pods are ready to accept request for a model + pods, err := s.cache.GetPodsForModel(model)
pkg/plugins/gateway/gateway.go
26
Go
0.071
question
37
51
51
false
Handle terminating pod for request routing
549
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
"description": "Average generation throughput in tokens/s.", "value": overrides.get("avg_generation_throughput", avg_generation_throughput) }, { "name": "gpu_cache_usage_perc", "type": "gauge", "description": "GPU KV-cache usage. 1 means 100 pe...
do you have dynamic lora information, should it be a rendered template with lora names?
"description": "Average generation throughput in tokens/s.", "value": overrides.get("avg_generation_throughput", avg_generation_throughput) }, { "name": "gpu_cache_usage_perc", "type": "gauge", "description": "GPU KV-cache usage. 1 means 100 pe...
@@ -535,7 +535,11 @@ def metrics(): ] # Generate all metrics - metrics_output = "" + metrics_output = """ +# HELP vllm:lora_requests_info Running stats on lora requests. +# TYPE vllm:lora_requests_info gauge +vllm:lora_requests_info{max_lora="1",running_lora_adapters="text2sql-lora-1",waiting_lora_ada...
development/app/app.py
26
Python
0.286
question
88
51
51
false
Mock app log fix for missing metrics warning
564
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
if !ok { continue } if model["id"] == instance.Name { return true, nil } } return false, nil } // Separate method to load the LoRA adapter func (r *ModelAdapterReconciler) loadModelAdapter(host string, instance *modelv1alpha1.ModelAdapter) error { artifactURL := instance.Spec.ArtifactURL if strings....
We can communicate later on how to also support the model on TOS. At present, the `/v1/model/download` interface provided on the runtime should come in handy. Let's create an issue to discuss about it
var response map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { return false, err } data, ok := response["data"].([]interface{}) if !ok { return false, errors.New("invalid data format") } for _, item := range data { model, ok := item.(map[string]interface{}) if ...
@@ -599,10 +611,11 @@ func (r *ModelAdapterReconciler) modelAdapterExists(host string, instance *model } // Separate method to load the LoRA adapter -func (r *ModelAdapterReconciler) loadModelAdapter(host string, instance *modelv1alpha1.ModelAdapter) error { +func (r *ModelAdapterReconciler) loadModelAdapter(url st...
pkg/controller/modeladapter/modeladapter_controller.go
26
Go
0.643
suggestion
200
51
51
false
Support model registration flow using aibrix runtime api
580
vllm-project/aibrix
2,572
Go
brosoul
Jeffwan
prometheus_multiproc_dir = os.environ["PROMETHEUS_MULTIPROC_DIR"] # Note: ensure it will be automatically cleaned up upon exit. path = Path(prometheus_multiproc_dir) path.mkdir(parents=True, exist_ok=True) if path.is_dir(): for item in path.iterdir(): if item.is_dir(): ...
Is it better to add a conversion of `lower()` for `request_headers` here?
else: prometheus_multiproc_dir = os.environ["PROMETHEUS_MULTIPROC_DIR"] # Note: ensure it will be automatically cleaned up upon exit. path = Path(prometheus_multiproc_dir) path.mkdir(parents=True, exist_ok=True) if path.is_dir(): for item in path.iterdir(): if item.is_di...
@@ -56,8 +57,27 @@ def initial_prometheus_multiproc_dir(): os.environ["PROMETHEUS_MULTIPROC_DIR"] = envs.PROMETHEUS_MULTIPROC_DIR +# filter_and_set_headers only keeps necessary headers +def filter_and_set_headers(request_headers): + # Create a new Headers object to ensure proper case-insensitive handling + ...
python/aibrix/aibrix/app.py
26
Python
0.429
question
73
51
51
false
Support model registration flow using aibrix runtime api
580
vllm-project/aibrix
2,572
Go
brosoul
Jeffwan
}, { "name": "gpu_cache_usage_perc", "type": "gauge", "description": "GPU KV-cache usage. 1 means 100 percent usage.", "value": overrides.get( "gpu_cache_usage_perc", gpu_cache_usage_perc ) }, { "name...
em. does user register a different name here?
}, { "name": "gpu_cache_usage_perc", "type": "gauge", "description": "GPU KV-cache usage. 1 means 100 percent usage.", "value": overrides.get( "gpu_cache_usage_perc", gpu_cache_usage_perc ) }, { "name...
@@ -566,16 +566,19 @@ def metrics(): ] # Generate all metrics - metrics_output = """ -# HELP vllm:lora_requests_info Running stats on lora requests. -# TYPE vllm:lora_requests_info gauge -vllm:lora_requests_info{max_lora="1",running_lora_adapters="text2sql-lora-1",waiting_lora_adapters=""} 1 -""" + me...
development/app/app.py
26
Python
0.143
question
45
51
51
false
Update routers to use GetPodModelMetric api and misc cleanup in metri…
590
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
if len(evt.Choices) == 0 { // Do not overwrite model, res can be empty. usage = evt.Usage } } if err := streaming.Err(); err != nil { klog.ErrorS(err, "error to unmarshal response", "requestID", requestID, "responseBody", string(b.ResponseBody.GetBody())) complete = true return generateErrorR...
This check is used to handle error messages from the vLLM model. I assumed "model" from request header should equal to "res.Model" returned from the response. If that is not the case, replacing with len(res.Model) == 0 is ok.
if len(evt.Choices) == 0 { // Do not overwrite model, res can be empty. usage = evt.Usage } } if err := streaming.Err(); err != nil { klog.ErrorS(err, "error to unmarshal response", "requestID", requestID, "responseBody", string(b.ResponseBody.GetBody())) complete = true return generateErrorR...
@@ -410,17 +410,18 @@ func (s *Server) HandleResponseBody(ctx context.Context, requestID string, req * Key: "x-error-response-unmarshal", RawValue: []byte("true"), }}}, err.Error()), complete - } else if res.Model != model {
pkg/plugins/gateway/gateway.go
26
Go
0.643
suggestion
226
51
51
false
Patch release for older vllm engine lora support in gateway plugins
599
vllm-project/aibrix
2,572
Go
zhangjyr
varungup90
"github.com/google/uuid" "github.com/openai/openai-go" "github.com/openai/openai-go/packages/ssestream" "github.com/redis/go-redis/v9" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" "github.com/aibrix/aibrix/pkg/cache" r...
x-error-user and x-error-streaming
"github.com/google/uuid" "github.com/openai/openai-go" "github.com/openai/openai-go/packages/ssestream" "github.com/redis/go-redis/v9" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" "github.com/aibrix/aibrix/pkg/cache" r...
@@ -48,14 +48,72 @@ import ( healthPb "google.golang.org/grpc/health/grpc_health_v1" ) +const ( + HeaderIncorrectRouting = "x-incorrect-routing-strategy" + + // General Error Headers + HeaderUserError = "x-user-error"
pkg/plugins/gateway/gateway.go
26
Go
0.286
suggestion
34
51
51
false
[misc] Polish gateway code with better structure
645
vllm-project/aibrix
2,572
Go
varungup90
Jeffwan
const ( HeaderIncorrectRouting = "x-incorrect-routing-strategy" // General Error Headers HeaderUserError = "x-user-error" HeaderRequestBodyProcessingError = "x-request-body-processing-error" HeaderErrorRouting = "x-error-routing" HeaderStreamingError = "x-streaming-erro...
right now words are not in order, we can it this way x-error-* x-update-* x-exceeded-*
const ( HeaderErrorInvalidRouting = "x-error-invalid-routing-strategy" // General Error Headers HeaderErrorUser = "x-error-user" HeaderErrorRouting = "x-error-routing" HeaderErrorRequestBodyProcessing = "x-error-request-body-processing" HeaderErrorResponseUnmarshal = "x-error-r...
@@ -48,14 +48,72 @@ import ( healthPb "google.golang.org/grpc/health/grpc_health_v1" ) +const ( + HeaderIncorrectRouting = "x-incorrect-routing-strategy" + + // General Error Headers + HeaderUserError = "x-user-error" + HeaderRequestBodyProcessingError = "x-request-body-processing-error" + HeaderE...
pkg/plugins/gateway/gateway.go
26
Go
0.357
suggestion
91
51
51
false
[misc] Polish gateway code with better structure
645
vllm-project/aibrix
2,572
Go
varungup90
Jeffwan
if !s.cache.CheckModelExists(model) { klog.ErrorS(nil, "model doesn't exist in cache, probably wrong model name", "requestID", requestID, "model", model) return generateErrorResponse(envoyTypePb.StatusCode_BadRequest, []*configPb.HeaderValueOption{{Header: &configPb.HeaderValue{ Key: HeaderNoModelDeployment...
both stream ones are errrors, should be updated to x-error-stream-*
if !s.cache.CheckModelExists(model) { klog.ErrorS(nil, "model doesn't exist in cache, probably wrong model name", "requestID", requestID, "model", model) return generateErrorResponse(envoyTypePb.StatusCode_BadRequest, []*configPb.HeaderValueOption{{Header: &configPb.HeaderValue{ Key: HeaderErrorNoModelBacke...
@@ -267,15 +331,15 @@ func (s *Server) HandleRequestBody(ctx context.Context, requestID string, req *e klog.ErrorS(nil, "no stream option available", "requestID", requestID, "jsonMap", jsonMap) return generateErrorResponse(envoyTypePb.StatusCode_InternalServerError, []*configPb.HeaderValueOption{{Header: &...
pkg/plugins/gateway/gateway.go
26
Go
0.429
suggestion
67
51
51
false
[misc] Polish gateway code with better structure
645
vllm-project/aibrix
2,572
Go
varungup90
Jeffwan
// Spec defines the desired behavior of the PodAutoscaler. Spec PodAutoscalerSpec `json:"spec,omitempty"` // Status represents the current information about the PodAutoscaler. Status PodAutoscalerStatus `json:"status,omitempty"` } // PodAutoscalerSpec defines the desired state of PodAutoscaler type PodAutoscalerS...
user has to specify one metric to help autoscaling decide the next steps. I think this should be required?
Spec PodAutoscalerSpec `json:"spec,omitempty"` // Status represents the current information about the PodAutoscaler. Status PodAutoscalerStatus `json:"status,omitempty"` } // PodAutoscalerSpec defines the desired state of PodAutoscaler type PodAutoscalerSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired sta...
@@ -57,16 +56,19 @@ type PodAutoscalerSpec struct { //PodSelector *metav1.LabelSelector `json:"podSelector,omitempty"` // MinReplicas is the minimum number of replicas to which the target can be scaled down. + // +optional MinReplicas *int32 `json:"minReplicas,omitempty"` // MaxReplicas is the maximum numbe...
api/autoscaling/v1alpha1/podautoscaler_types.go
26
Go
0.429
question
106
51
51
false
fix api scheme
674
vllm-project/aibrix
2,572
Go
Jeffwan
kerthcet
you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS...
The original design here is to refer a model. but we didn't add the model CRD here (due to the reason I synced with you earlier). I feel there're two options 1. Once we have the model api, baseModel can ref that object. 2. at this moment, we probably can leverage PodSelector or objectRef to upgrade the `PodSelector...
you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS...
@@ -21,15 +21,13 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // ModelAdapterSpec defines the desired state of ModelAdapter type...
api/model/v1alpha1/modeladapter_types.go
26
Go
0.643
suggestion
439
51
51
false
fix api scheme
674
vllm-project/aibrix
2,572
Go
Jeffwan
kerthcet
option.WithMaxRetries(0), respOpt, ) } func validateInference(t *testing.T, modelName string) { client := createOpenAIClient(gatewayURL, apiKey) validateInferenceWithClient(t, client, modelName) } func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName string) { chatCompletion, err := ...
I can not find reference here, is this being used?
/* Copyright 2024 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar...
@@ -101,3 +110,38 @@ func createOpenAIClientWithRoutingStrategy(baseURL, apiKey, routingStrategy stri respOpt, ) } + +func validateInference(t *testing.T, modelName string) { + client := createOpenAIClient(gatewayURL, apiKey) + validateInferenceWithClient(t, client, modelName) +} + +func validateInferenceWithClie...
test/e2e/util.go
26
Go
0.286
question
50
40
133
false
Add model adapter e2e tests
701
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
return &extProcPb.ProcessingResponse{ Response: &extProcPb.ProcessingResponse_ResponseHeaders{ ResponseHeaders: &extProcPb.HeadersResponse{ Response: &extProcPb.CommonResponse{ HeaderMutation: &extProcPb.HeaderMutation{ SetHeaders: headers, }, ClearRouteCache: true, }, }, }, } }...
in this case, we do not have any meaningful information right?
Header: &configPb.HeaderValue{ Key: HeaderTargetPod, RawValue: []byte(targetPodIP), }, }) } var isProcessingError bool var processingErrorCode int for _, headerValue := range b.ResponseHeaders.Headers.Headers { if headerValue.Key == ":status" { code, _ := strconv.Atoi(string(headerValue.R...
@@ -421,6 +423,39 @@ func (s *Server) HandleResponseHeaders(ctx context.Context, requestID string, re }) } + var isProcessingError bool + var processingErrorCode int + for _, headerValue := range b.ResponseHeaders.Headers.Headers { + if headerValue.Key == ":status" { + code, _ := strconv.Atoi(string(headerVal...
pkg/plugins/gateway/gateway.go
26
Go
0.214
question
63
51
51
false
Process response headers in gateway
703
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
package e2e import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/assert" modelv1alpha1 "github.com/vllm-project/aibrix/api/model/v1alpha1" v1alpha1 "github.com/vllm-project/aibrix/pkg/client/clientset/versioned" apierrors "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis...
@gangmuk reports missing license header failed the check. However, license check job was not triggered. not sure what's the problem. https://github.com/vllm-project/aibrix/issues/723 good to see it's added now
/* Copyright 2024 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
@@ -1,3 +1,19 @@ +/*
test/e2e/model_adapter_test.go
1
Go
0.429
bug
212
26
26
false
Process response headers in gateway
703
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
Key: HeaderWentIntoReqHeaders, RawValue: []byte("true"), }, }} if targetPodIP != "" { headers = append(headers, &configPb.HeaderValueOption{ Header: &configPb.HeaderValue{ Key: HeaderTargetPod, RawValue: []byte(targetPodIP), }, }) } return &extProcPb.ProcessingResponse{ Respon...
30x redirection are successful codes. Seems we will never have such case? Is it possible to have 20x? here? better to have a helper method and let's consider those cases
func (s *Server) HandleResponseHeaders(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest, targetPodIP string) (*extProcPb.ProcessingResponse, bool, int) { klog.InfoS("-- In ResponseHeaders processing ...", "requestID", requestID) b := req.Request.(*extProcPb.ProcessingRequest_ResponseHeaders) ...
@@ -421,6 +428,24 @@ func (s *Server) HandleResponseHeaders(ctx context.Context, requestID string, re }) } + var isProcessingError bool + var processingErrorCode int + for _, headerValue := range b.ResponseHeaders.Headers.Headers { + if headerValue.Key == ":status" { + code, _ := strconv.Atoi(string(headerVal...
pkg/plugins/gateway/gateway.go
26
Go
0.429
refactor
170
51
51
false
Process response headers in gateway
703
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
) text_chunks = [] prompt_tokens = 0 output_tokens = 0 total_tokens = 0 async for chunk in stream: if chunk.choices: if chunk.choices[0].delta.content is not None: if not first_response_time: ...
result record seems like a little bit duplicated. this is ok at this moment.
) text_chunks = [] prompt_tokens = 0 output_tokens = 0 total_tokens = 0 async for chunk in stream: if chunk.choices: if chunk.choices[0].delta.content is not None: if not first_response_time: ...
@@ -46,25 +46,43 @@ async def send_request_streaming(client: openai.AsyncOpenAI, output_tokens = chunk.usage.completion_tokens total_tokens = chunk.usage.total_tokens response = "".join(text_chunks) - response_time = asyncio.get_event_loop().time() - late...
benchmarks/client/client.py
26
Python
0.214
refactor
77
51
51
false
Recording failed requests in benchmark client
727
vllm-project/aibrix
2,572
Go
Jeffwan
gangmuk
func (n *TreeNode) GetDepth() int { return n.depth } func (n *TreeNode) GetID() int { return n.id } func (n *TreeNode) GetChildren() map[int]*TreeNode { return n.children } func (n *TreeNode) ResetEvictedPods() { n.evictedPods = make(map[int]bool) } func (n *TreeNode) ResetCachedPods() { n.cachedPods = make(m...
you can update the comments later.
func (n *TreeNode) GetDepth() int { return n.depth } func (n *TreeNode) GetID() int { return n.id } func (n *TreeNode) GetChildren() map[int]*TreeNode { return n.children } func (n *TreeNode) ResetEvictedPods() { n.evictedPods = make(map[int]bool) } func (n *TreeNode) ResetCachedPods() { n.cachedPods = make(m...
@@ -72,6 +112,114 @@ func (n *TreeNode) GetDepth() int { return n.depth } +func (n *TreeNode) GetID() int { + return n.id +} + +func (n *TreeNode) GetChildren() map[int]*TreeNode { + return n.children +} + +func (n *TreeNode) ResetEvictedPods() { + n.evictedPods = make(map[int]bool) +} + +func (n *TreeNode) ResetC...
pkg/plugins/gateway/prefixcacheindexer/tree.go
26
Go
0.071
suggestion
34
51
51
false
Improve thread safety for TreeNode data structure and refactor related codes
730
vllm-project/aibrix
2,572
Go
varungup90
gangmuk
client = openai.AsyncOpenAI( api_key=args.api_key, base_url=args.endpoint + "/v1", ) if args.routing_strategy is not None: client.default_headers["routing-strategy"] = args.routing_strategy if not args.streaming: logging.info("Using batch c...
em. that's something we didn't review clearly. good fix
cur_time = time.time() target_time = base_time + ts / 1000.0 logging.warning(f"Prepare to launch {len(requests)} batched tasks after {target_time - cur_time}") if target_time > cur_time: await asyncio.sleep(target_time - cur_time) formatted_prompts = [wrap_prompt_as_c...
@@ -199,7 +219,9 @@ def main(args): base_url=args.endpoint + "/v1", ) if args.routing_strategy is not None: - client.default_headers["routing-strategy"] = args.routing_strategy + client = client.with_options(
benchmarks/client/client.py
26
Python
0.214
suggestion
55
45
51
false
[fix] fixing bug in using AsyncOpenAI client (header setting, token counting, etc)
738
vllm-project/aibrix
2,572
Go
Jeffwan
gangmuk
current_value = round(trend + noise) if pattern_config['only_rise']: current_value = max(prev_value, current_value) prev_value = current_value return current_value, prev_value assert duration_ms is not None and interval_ms is not None, \ "duration_ms and inte...
Concurrency could be the misleading term here. As far as I know, concurrency or concurrent requests usually means (the number of) requests that are concurrently running in the system. For example, concurrency control is controlling that. By that definition, workload generator can't control concurrency. So what it meant...
current_value = round(trend + noise) if pattern_config['only_rise']: current_value = max(prev_value, current_value) prev_value = current_value return current_value, prev_value assert duration_ms is not None and interval_ms is not None, \ "duration_ms and inte...
@@ -242,32 +246,33 @@ def math_function(t, pattern_config, length, prev_value): previous_input_len = -1 previous_output_len = -1 ts = 0 - base_req_id = 0 - sharegpt_df = load_requests(dataset_path=prompt_file_path, tokenizer=tokenizer) + rps_dist = [] + input_token_len_dist = [] + ou...
benchmarks/generator/workload_generator.py
26
Python
0.5
suggestion
395
51
51
false
Reconfigure workload generator for predefined synthetic patterns
771
vllm-project/aibrix
2,572
Go
gangmuk
happyandslow
klog.Infof("using default prefix cache match threshold percent: %d", defaultPrefixCacheMatchThresholdPercent) return defaultPrefixCacheMatchThresholdPercent } type prefixCacheRouter struct { prefixCacheIndexer prefixcacheindexer.PrefixCacheIndexer } func NewPrefixCacheRouter() (Router, error) { return prefixCache...
Can we have some interface here so we can probably configure it for differenc scenarios? My concern is I think it's ok to split by `" "` for english,, for some other languages like chinese, this might not be helpful.
if value != "" { intValue, err := strconv.Atoi(value) if err != nil || intValue <= 0 || intValue > 100 { klog.Infof("invalid AIBRIX_PREFIX_CACHE_MATCH_THRESHOLD_PERCENT: %s, valid value between 0 and 100, failing back to default", value) } else { klog.Infof("using AIBRIX_PREFIX_CACHE_MATCH_THRESHOLD_PERCEN...
@@ -72,10 +73,7 @@ func (p prefixCacheRouter) Route(ctx context.Context, pods map[string]*v1.Pod, m } } - tokens, err := utils.TokenizeInputText(message) - if err != nil { - return "", err - } + tokens := strings.Split(message, " ")
pkg/plugins/gateway/algorithms/prefix_cache.go
26
Go
0.571
question
218
51
51
false
Use string based tokenizer in prefix cache
774
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
type Cache struct { mu sync.RWMutex redisClient *redis.Client prometheusApi prometheusv1.API initialized bool subscribers []metrics.MetricSubscriber metrics map[string]interface{} ModelMetrics map[string]map[string]interface{} Pods map[string]*v1....
I am thinking if we want to add a aibrix label like `orchestration.aibrix.ai/server-pod`. autoscaling need that feature as well. We can start with ray specific label and replace with our own later as a separate issue
type Cache struct { mu sync.RWMutex redisClient *redis.Client prometheusApi prometheusv1.API initialized bool subscribers []metrics.MetricSubscriber metrics map[string]interface{} ModelMetrics map[string]map[string]interface{} Pods map[string]*v1....
@@ -75,6 +75,7 @@ type Block struct { const ( modelIdentifier = "model.aibrix.ai/name" + nodeType = "ray.io/node-type"
pkg/cache/cache.go
26
Go
0.643
suggestion
218
51
51
false
Ignore worker pods for gateway routing
776
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
"net/http" "github.com/gorilla/mux" "github.com/redis/go-redis/v9" "github.com/vllm-project/aibrix/pkg/cache" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) type httpServer struct { redisClient *redis.Client cache *cache.Cache } func NewHTTPServer(addr string, redis *redis.Client) *http....
These are user related handlers.
"net/http" "github.com/gorilla/mux" "github.com/redis/go-redis/v9" "github.com/vllm-project/aibrix/pkg/cache" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) type httpServer struct { redisClient *redis.Client cache *cache.Cache } func NewHTTPServer(addr string, redis *redis.Client) *http....
@@ -45,10 +45,12 @@ func NewHTTPServer(addr string, redis *redis.Client) *http.Server { cache: c, } r := mux.NewRouter() + // Rate Limit related handlers
pkg/metadata/handlers.go
26
Go
0.286
suggestion
32
51
51
false
Support OpenAI api style /v1/models response
829
vllm-project/aibrix
2,572
Go
varungup90
Jeffwan
// +kubebuilder:validation:Optional // +kubebuilder:default:="IfNotPresent" ImagePullPolicy string `json:"imagePullPolicy,omitempty"` // shared memory size for kvcach // +kubebuilder:validation:Optional // +kubebuilder:default:="" SharedMemorySize string `json:"sharedMemorySize,omitempty"` // kvcache environm...
we can use annotation to control it for short term, we can have an `v1alpha2` version for spec change later. seems your changes below doesn't leverage this yet.
// +kubebuilder:validation:Optional // +kubebuilder:default:="IfNotPresent" ImagePullPolicy string `json:"imagePullPolicy,omitempty"` // shared memory size for kvcach // +kubebuilder:validation:Optional // +kubebuilder:default:="" SharedMemorySize string `json:"sharedMemorySize,omitempty"` // kvcache environm...
@@ -104,6 +104,26 @@ type CacheSpec struct { CPU string `json:"cpu,omitempty"` } +type AffinityConfig struct {
api/orchestration/v1alpha1/kvcache_types.go
26
Go
0.571
suggestion
160
51
51
false
Added antiaffinity in kvcache crd
865
vllm-project/aibrix
2,572
Go
Jeffwan
gangmuk
{ LabelSelector: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ { Key: "model.aibrix.ai/name", Operator: metav1.LabelSelectorOpIn, Values: []string{value}, }, }, }, TopologyKey: "kubernetes.io/hostname", }, }...
what's the usage here? do you want to apply anti-affinity to other engine pods or just kv cache pod? the cache pod doesn't have `model.aibrix.ai/name` labels, right?
{ LabelSelector: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ { Key: "model.aibrix.ai/name", Operator: metav1.LabelSelectorOpIn, Values: []string{value}, }, }, }, TopologyKey: "kubernetes.io/hostname", }, }...
@@ -463,6 +465,52 @@ func (r *KVCacheReconciler) reconcileDeployment(ctx context.Context, kvCache *or affinity.PodAffinity = podAffinity } + // Add pod anti-affinity handling + if value, ok := kvCache.Annotations[KVCacheAnnotationPodAntiAffinityKey]; ok { + podAntiAffinity := &corev1.PodAntiAffinity{ + Requir...
pkg/controller/kvcache/kvcache_controller.go
26
Go
0.5
performance
170
51
51
false
Added antiaffinity in kvcache crd
865
vllm-project/aibrix
2,572
Go
Jeffwan
gangmuk
func TestLRUStore_TTL(t *testing.T) { store := NewLRUStore[string, string](2, 2*time.Second, 1*time.Second) // Test TTL expiration store.Put("key1", "value1") time.Sleep(3 * time.Second) // Wait for TTL to expire if _, ok := store.Get("key1"); ok { t.Errorf("expected key1 to be expired") } } func TestLRUSto...
Can you also add a test to validate least recently used key is evicted?
func TestLRUStore_TTL(t *testing.T) { store := NewLRUStore[string, string](2, 2*time.Second, 1*time.Second, DefaultGetCurrentTime) // Test TTL expiration store.Put("key1", "value1") time.Sleep(3 * time.Second) // Wait for TTL to expire if _, ok := store.Get("key1"); ok { t.Errorf("expected key1 to be expired"...
@@ -0,0 +1,105 @@ +/* +Copyright 2025 The Aibrix Team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agre...
pkg/plugins/gateway/cache/lru_store_test.go
26
Go
0.286
question
71
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and ...
increase the default block size to 1 million.
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and ...
@@ -23,24 +23,42 @@ import ( "time" "github.com/cespare/xxhash/v2" + "github.com/vllm-project/aibrix/pkg/plugins/gateway/cache" "github.com/vllm-project/aibrix/pkg/utils" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" ) const ( + defaultPrefixCacheBlockNumber = 100
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.071
suggestion
45
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pr...
you can rename the variable to defaultPrefixCacheEvictionInternalInSec
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pr...
@@ -23,24 +23,42 @@ import ( "time" "github.com/cespare/xxhash/v2" + "github.com/vllm-project/aibrix/pkg/plugins/gateway/cache" "github.com/vllm-project/aibrix/pkg/utils" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" ) const ( + defaultPrefixCacheBlockNumber = 100 defaultPrefixCacheBlockSize ...
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.286
performance
70
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and...
Right now the structure is as follows hash1 -> model1 -> pod1 + pod1 last access time -> model1 -> pod2 + pod2 last access time -> model2 -> pod3 + pod3 last access time -> blocks last access time Right now eviction is based of last blocks access time. I kept the eviction l...
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and...
@@ -0,0 +1,159 @@ +/* +Copyright 2025 The Aibrix Team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agre...
pkg/plugins/gateway/cache/lru_store.go
26
Go
0.5
suggestion
664
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
} func (e *LRUStore[K, V]) evict(now time.Time) { var keysToEvict []K e.Lock() for key, entry := range e.freeTable { if now.Sub(entry.lastAccessTime) > e.ttl { keysToEvict = append(keysToEvict, key) } } e.Unlock() for _, key := range keysToEvict { e.Lock() if entry, exists := e.freeTable[key]; exist...
here. I am curious whether it need key level lock? could it be for loop level?
e.lruList.moveToHead(entry) return entry.Value, true } var zero V return zero, false } func (e *LRUStore[K, V]) Len() int { e.RLock() defer e.RUnlock() return len(e.freeTable) } func (e *LRUStore[K, V]) evict(now time.Time) { var keysToEvict []K e.RLock() for key, entry := range e.freeTable { if now.S...
@@ -0,0 +1,159 @@ +/* +Copyright 2025 The Aibrix Team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agre...
pkg/plugins/gateway/cache/lru_store.go
26
Go
0.286
question
79
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
Jeffwan
vie-serendipity
/* Copyright 2025 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
if this is empty, tail.prev==head. does it still remove elements? Should we check ``` if l.tail.prev == l.head { return nil } ```
e.next = l.head.next l.head.next.prev = e l.head.next = e } func (l *list[K, V]) moveToHead(e *entry[K, V]) { l.remove(e) l.addToHead(e) } func (l *list[K, V]) remove(e *entry[K, V]) { if e.prev != nil { e.prev.next = e.next } if e.next != nil { e.next.prev = e.prev } e.prev = nil e.next = nil } func ...
@@ -0,0 +1,159 @@ +/* +Copyright 2025 The Aibrix Team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agre...
pkg/plugins/gateway/cache/lru_store.go
26
Go
0.786
suggestion
142
160
30
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
Jeffwan
vie-serendipity
/* Copyright 2025 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
RWMutex for `Get()` or `Len()` Operations?
/* Copyright 2025 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
@@ -0,0 +1,159 @@ +/* +Copyright 2025 The Aibrix Team. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agre...
pkg/plugins/gateway/cache/lru_store.go
25
Go
0.214
question
42
50
50
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
Jeffwan
vie-serendipity
} } klog.Infof("using default prefix cache eviction interval: %d ms", defaultPrefixCacheEvictionInternalInMS) return defaultPrefixCacheEvictionInternalInMS * time.Millisecond } func getPrefixCacheEvictionDuration() time.Duration { value := utils.LoadEnv("AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS", "") if value...
Using cache interface here to replace blocks looks better. this is great
} } klog.Infof("using default prefix cache eviction interval: %d ms", defaultPrefixCacheEvictionInternalInSec) return defaultPrefixCacheEvictionInternalInSec * time.Second } func getPrefixCacheEvictionDuration() time.Duration { value := utils.LoadEnv("AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS", "") if value !=...
@@ -87,33 +105,27 @@ func getPrefixCacheEvictionDuration() time.Duration { } type PrefixHashTable struct { - mu sync.RWMutex - blocks map[uint64]Block - hash *xxhash.Digest - seed uint64 + mu sync.RWMutex + hash *xxhash.Digest + seed uint64 + store cache.Store[uint64, Block]
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.286
performance
72
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
Jeffwan
vie-serendipity
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and ...
this value determines the size of the cache, I feel 100 is too small. We need to change default one to large values. Later, the prefix will be changed to use character instead of word or tokens, results in more blocks. 20000 token request end up with 1250 blocks. we can roughly calculate the memory size (like 1GiB) a...
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and ...
@@ -23,24 +23,42 @@ import ( "time" "github.com/cespare/xxhash/v2" + "github.com/vllm-project/aibrix/pkg/plugins/gateway/cache" "github.com/vllm-project/aibrix/pkg/utils" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" ) const ( + defaultPrefixCacheBlockNumber = 100
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
1
performance
701
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
Jeffwan
vie-serendipity
} else { klog.Infof("using AIBRIX_PREFIX_CACHE_BLOCK_NUMBER env value for prefix cache block number: %d", intValue) return intValue } } klog.Infof("using default prefix cache block number: %d", defaultPrefixCacheBlockNumber) return defaultPrefixCacheBlockNumber } func getPrefixCacheBlockSize() int { valu...
nit: Secs -> SECONDS or SECS (prefer first one)
} else { klog.Infof("using AIBRIX_PREFIX_CACHE_BLOCK_NUMBER env value for prefix cache block number: %d", intValue) return intValue } } klog.Infof("using default prefix cache block number: %d", defaultPrefixCacheBlockNumber) return defaultPrefixCacheBlockNumber } func getPrefixCacheBlockSize() int { valu...
@@ -57,18 +75,18 @@ func getPrefixCacheBlockSize() int { } func getPrefixCacheEvictionInterval() time.Duration { - value := utils.LoadEnv("AIBRIX_PREFIX_CACHE_EVICTION_INTERVAL_MS", "") + value := utils.LoadEnv("AIBRIX_PREFIX_CACHE_EVICTION_INTERVAL_Secs", "")
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.143
suggestion
47
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
klog.Infof("using AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS env value for prefix cache eviction duration: %d ms", intValue) return time.Duration(intValue) * time.Minute } } klog.Infof("using default prefix cache eviction duration: %d mins", defaultPrefixCacheEvictionDurationInMins) return defaultPrefixCache...
nit: since variables are already assigned, use them directly.
klog.Infof("using AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS env value for prefix cache eviction duration: %d ms", intValue) return time.Duration(intValue) * time.Minute } } klog.Infof("using default prefix cache eviction duration: %d mins", defaultPrefixCacheEvictionDurationInMins) return defaultPrefixCache...
@@ -87,33 +105,27 @@ func getPrefixCacheEvictionDuration() time.Duration { } type PrefixHashTable struct { - mu sync.RWMutex - blocks map[uint64]Block - hash *xxhash.Digest - seed uint64 + mu sync.RWMutex + hash *xxhash.Digest + seed uint64 + store cache.Store[uint64, Block] } type Block struct { -...
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.286
nitpick
61
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
getPrefixCacheEvictionDuration(), getPrefixCacheEvictionInterval()), } return instance } // returns matchedTokens, unMatchedTokens, matchedPods func (c *PrefixHashTable) MatchPrefix(tokens []byte, model string, pods []*v1.Pod) ([]byte, []byte, []*v1.Pod) { c.mu.Lock() defer c.mu.Unlock() var block, lastMat...
store is thread-safe, so we can remove lock from line 134 now. Right?
prefixCacheEvictionDuration, prefixCacheEvictionInterval, func() time.Time { return time.Now() }), } return instance } // returns matchedTokens, unMatchedTokens, matchedPods func (c *PrefixHashTable) MatchPrefix(tokens []byte, model string, pods []*v1.Pod) ([]byte, []byte, []*v1.Pod) { var block, lastMatc...
@@ -134,17 +146,15 @@ func (c *PrefixHashTable) MatchPrefix(tokens []byte, model string, pods []*v1.Po _, _ = c.hash.Write(tokens[i:end]) prefixHash := c.hash.Sum64() c.hash.ResetWithSeed(c.seed) - - block, ok = c.blocks[prefixHash] + block, ok = c.store.Get(prefixHash)
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.429
question
69
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
{ObjectMeta: metav1.ObjectMeta{Name: "p1"}}, {ObjectMeta: metav1.ObjectMeta{Name: "p2"}}, } inputText := "Hello World! What a Good Day! Good day to code and learn new things in LLM!! 你好世界! 多么美好的一天啊!" tokens, err := tokenizer.NewStringTokenizer().TokenizeInputText(inputText) assert.NoError(t, err) matchedToke...
In the test, we can not sleep for 25 seconds. Can you add a mock for time or update the env variable in test for lower value.
} pods := []*v1.Pod{ {ObjectMeta: metav1.ObjectMeta{Name: "p1"}}, {ObjectMeta: metav1.ObjectMeta{Name: "p2"}}, } inputText := "Hello World! What a Good Day! Good day to code and learn new things in LLM!! 你好世界! 多么美好的一天啊!" tokens, err := tokenizer.NewStringTokenizer().TokenizeInputText(inputText) assert.NoErro...
@@ -63,7 +64,7 @@ func Test_PrefixHashTableE2E(t *testing.T) { assert.Equal(t, 0, len(unMatchedTokens)) assert.Equal(t, "p1", matchPods[0].Name) - cache.Evict(time.Now().Add(60 * time.Minute)) + time.Sleep(25 * time.Second)
pkg/plugins/gateway/prefixcacheindexer/hash_test.go
26
Go
0.357
suggestion
125
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
modelToPods map[string]map[string]time.Time // model_name: map[pod_name]pod_last_access_time lastAccessTime time.Time // block_last_access_time } func NewPrefixHashTable() PrefixCacheIndexer { r := rand.New(rand.NewSource(time.Now().Unix())) seed := r.Uint64() instance := &PrefixHashTable...
@vie-serendipity I assumed LRU store is thread-safe and removing this lock was fine. While working on PR #933 I came across the bug for concurrent read/write for blocks. I have added the lock back, if you get a chance, can you make LRU store thread-safe? Thank you.
klog.Infof("invalid AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS: %s, falling back to default", value) } else { klog.Infof("using AIBRIX_PREFIX_CACHE_EVICTION_DURATION_MINS env value for prefix cache eviction duration: %d ms", intValue) return time.Duration(intValue) * time.Minute } } klog.Infof("using def...
@@ -87,40 +105,33 @@ func getPrefixCacheEvictionDuration() time.Duration { } type PrefixHashTable struct { - mu sync.RWMutex - blocks map[uint64]Block - hash *xxhash.Digest - seed uint64 + mu sync.RWMutex + hash *xxhash.Digest + seed uint64 + store cache.Store[uint64, Block] } type Block struct { -...
pkg/plugins/gateway/prefixcacheindexer/hash.go
26
Go
0.571
bug
268
51
51
false
[API] [Misc]: Support LRU cache with TTL for prefix cache indexer
905
vllm-project/aibrix
2,572
Go
varungup90
vie-serendipity
cluster := clusters[i] wg.Add(1) go func(cluster rayclusterv1.RayCluster) { defer wg.Done() if err := r.Delete(ctx, &cluster); err != nil { if !apierrors.IsNotFound(err) { errCh <- fmt.Errorf("failed to delete pod: %w", err) } } r.Expectations.DeletionObserved(types.NamespacedName{Namespa...
using aggregated errors looks good to me.
const maxConcurrency = 10 semaphore := make(chan struct{}, maxConcurrency) for i := 0; i < diff; i++ { cluster := clusters[i] semaphore <- struct{}{} wg.Add(1) go func(cluster rayclusterv1.RayCluster) { defer wg.Done() defer func() { <-semaphore }() // release the semaphore if err := r.Delete(ctx, ...
@@ -192,13 +198,18 @@ func (r *RayClusterReplicaSetReconciler) scaleDown(ctx context.Context, replicas } wg.Wait() + close(errCh) - select { - case err := <-errCh: - return err - default: - return nil + // aggregate errors if any. + var aggregatedErrors []error + for err := range errCh { + aggregatedErrors =...
pkg/controller/rayclusterreplicaset/rayclusterreplicaset_controller.go
26
Go
0.214
suggestion
41
51
51
false
[Misc] chore(raycluster): add concurrency limit and error aggregation to scaleDown
914
vllm-project/aibrix
2,572
Go
Jeffwan
googs1025
if err := r.updateReplicaSetStatus(ctx, replicaset, newStatus, rsKey); err != nil { return reconcile.Result{}, err } return ctrl.Result{}, nil } // scaleUp handles RayCluster creation logic when scaling up func (r *RayClusterReplicaSetReconciler) scaleUp(ctx context.Context, replicaset *orchestrationv1alpha1.Ray...
it's ok to have a fixed value at this moment
if err := r.updateReplicaSetStatus(ctx, replicaset, newStatus, rsKey); err != nil { return reconcile.Result{}, err } return ctrl.Result{}, nil } // scaleUp handles RayCluster creation logic when scaling up func (r *RayClusterReplicaSetReconciler) scaleUp(ctx context.Context, replicaset *orchestrationv1alpha1.Ray...
@@ -176,12 +176,18 @@ func (r *RayClusterReplicaSetReconciler) scaleUp(ctx context.Context, replicaset func (r *RayClusterReplicaSetReconciler) scaleDown(ctx context.Context, replicaset *orchestrationv1alpha1.RayClusterReplicaSet, clusters []rayclusterv1.RayCluster, diff int) error { var wg sync.WaitGroup errCh :=...
pkg/controller/rayclusterreplicaset/rayclusterreplicaset_controller.go
26
Go
0.071
suggestion
44
51
51
false
[Misc] chore(raycluster): add concurrency limit and error aggregation to scaleDown
914
vllm-project/aibrix
2,572
Go
Jeffwan
googs1025
"time" "github.com/vllm-project/aibrix/pkg/metrics" "github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) const ( expireWriteRequestTraceIntervalInMins = 10 ) func (c *Store) getRequestTrace(modelName string) *RequestTrace { trace := NewRequestTrace(time.Now(...
For the log messages, you can add the requestID (add to routing context if not present) and pod name. Without these two fields, log message is not useful. Comment applies to all log messages in this function.
"time" "github.com/vllm-project/aibrix/pkg/metrics" "github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) const ( expireWriteRequestTraceIntervalInMins = 10 ) func (c *Store) getRequestTrace(modelName string) *RequestTrace { trace := NewRequestTrace(time.Now(...
@@ -41,6 +43,43 @@ func (c *Store) getRequestTrace(modelName string) *RequestTrace { return newer } +func (c *Store) addPodStats(ctx *types.RoutingContext) { + if !ctx.HasRouted() { + klog.Warning("request has not been routed, please route request first")
pkg/cache/cache_trace.go
26
Go
0.5
suggestion
211
51
51
false
[Misc] Add pods stats example: running requests.
918
vllm-project/aibrix
2,572
Go
varungup90
zhangjyr
"fmt" "sync/atomic" "time" "github.com/vllm-project/aibrix/pkg/metrics" "github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) const ( expireWriteRequestTraceIntervalInMins = 10 ) func (c *Store) getRequestTrace(modelName string) *RequestTrace { trace := New...
Is there a unit test to validate add pod stats, specially with concurrent requests.
"fmt" "sync/atomic" "time" "github.com/vllm-project/aibrix/pkg/metrics" "github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" "k8s.io/klog/v2" ) const ( expireWriteRequestTraceIntervalInMins = 10 ) func (c *Store) getRequestTrace(modelName string) *RequestTrace { trace := New...
@@ -41,6 +43,43 @@ func (c *Store) getRequestTrace(modelName string) *RequestTrace { return newer } +func (c *Store) addPodStats(ctx *types.RoutingContext) {
pkg/cache/cache_trace.go
26
Go
0.214
nitpick
83
51
51
false
[Misc] Add pods stats example: running requests.
918
vllm-project/aibrix
2,572
Go
varungup90
zhangjyr
func (c *Store) DoneRequestCount(ctx *types.RoutingContext, requestID string, modelName string, traceTerm int64) { if ctx != nil { c.donePodStats(ctx) } meta, ok := c.metaModels.Load(modelName) if ok { atomic.AddInt32(&meta.pendingRequests, -1) } // DoneRequest only works for current term, no need to retry....
Right now, done request trace is called in gateway_resp_body. I identified two scenario where a request can complete before executing resp_body. You can use this PR to address this gap. 1) If error code is returned in resp_headers. 2) If the client cancels the request and error is return from here `if err := srv.Se...
func (c *Store) DoneRequestCount(ctx *types.RoutingContext, requestID string, modelName string, traceTerm int64) { if ctx != nil { c.donePodStats(ctx, requestID) } meta, ok := c.metaModels.Load(modelName) if ok { atomic.AddInt32(&meta.pendingRequests, -1) } // DoneRequest only works for current term, no nee...
@@ -214,6 +222,10 @@ func (c *Store) DoneRequestCount(ctx *types.RoutingContext, requestID string, mo // outputTokens: Output tokens count // traceTerm: Trace term identifier func (c *Store) DoneRequestTrace(ctx *types.RoutingContext, requestID string, modelName string, inputTokens, outputTokens, traceTerm int64) {
pkg/cache/cache_impl.go
26
Go
0.786
suggestion
343
51
51
false
[Misc] Add pods stats example: running requests.
918
vllm-project/aibrix
2,572
Go
varungup90
zhangjyr
import argparse import logging import time import asyncio import openai import json import io import traceback from typing import List from utils import (load_workload, wrap_prompt_as_chat_message) logging.basicConfig(level=logging.INFO) async def send_request_streaming(client: openai.AsyncOpenAI, ...
is multi-threading necessary for this client?
import argparse import logging import time import asyncio import openai import json import io import traceback import threading from queue import Queue from concurrent.futures import ThreadPoolExecutor from typing import List from utils import (load_workload, wrap_prompt_as_chat_message) logging.basicConfig(level=lo...
@@ -6,25 +6,50 @@ import json import io import traceback +import threading +from queue import Queue +from concurrent.futures import ThreadPoolExecutor from typing import List from utils import (load_workload, wrap_prompt_as_chat_message) logging.basicConfig(level=logging.INFO) +task_queue = Queue() +thread_...
benchmarks/client/client.py
21
Python
0.214
question
47
46
46
false
Enable parallel client using thread pool in benchmark client
919
vllm-project/aibrix
2,572
Go
Jeffwan
happyandslow
var controllers string var modeladapterSchedulerPolicy string var enableRuntimeSidecar bool var debugMode bool flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint...
I am thinking should we use `model-adapter` or just `modeladapter`. I did see our controller name use hyphen. that's probably more readable since this is a user facing feature. what do you think?
var controllers string var modeladapterSchedulerPolicy string var enableRuntimeSidecar bool var debugMode bool flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint...
@@ -131,6 +133,7 @@ func main() { flag.StringVar(&leaderElectionId, "leader-election-id", "aibrix-controller-manager", "leader-election-id determines the name of the resource that leader election will use for holding the leader lock, Default is aibrix-controller-manager.") flag.StringVar(&controllers, "controlle...
cmd/controllers/main.go
26
Go
0.571
question
195
51
51
false
[CLI] feature(modeladapter): make modeladapter controller scheduler policy be configured
921
vllm-project/aibrix
2,572
Go
Jeffwan
googs1025
} } // ignore worker pods oldNodeType := oldPod.Labels[nodeType] newNodeType := newPod.Labels[nodeType] if oldNodeType == nodeWorker || newNodeType == nodeWorker { klog.InfoS("ignored ray worker pod", "old pod", oldPod.Name, "new pod", newPod.Name) return } // Add new mappings if present if newOk { me...
that's a good catch. I am considering whether it's better to use switch case for `cache.DeletedFinalStateUnknown` and `v1.Pod` which makes the code cleaner? something like this. otherwise the v1.pod-> cache.DeletedFinalStateUnknown -> v1.pod chain is kind of messy. ``` switch obj := obj.(type) { case *v1.Pod: ...
} } // ignore worker pods oldNodeType := oldPod.Labels[nodeType] newNodeType := newPod.Labels[nodeType] if oldNodeType == nodeWorker || newNodeType == nodeWorker { klog.InfoS("ignored ray worker pod", "old pod", oldPod.Name, "new pod", newPod.Name) return } // Add new mappings if present if newOk { me...
@@ -158,25 +158,49 @@ func (c *Store) updatePod(oldObj interface{}, newObj interface{}) { } func (c *Store) deletePod(obj interface{}) { - pod := obj.(*v1.Pod) - _, ok := pod.Labels[modelIdentifier] - _, existed := c.metaPods.Load(pod.Name) // Make sure nothing left. - if !ok && !existed { + var namespace, name str...
pkg/cache/informers.go
26
Go
1
performance
593
51
51
false
[BUG] cache: handle DeletedFinalStateUnknown by the delete func
926
vllm-project/aibrix
2,572
Go
Jeffwan
Iceber
return hasLabelAndModelIdentifier(e.ObjectNew.GetLabels(), labelKey) }, DeleteFunc: func(e event.DeleteEvent) bool { return hasLabelAndModelIdentifier(e.Object.GetLabels(), labelKey) }, GenericFunc: func(e event.GenericEvent) bool { return hasLabelAndModelIdentifier(e.Object.GetLabels(), labelKey) },...
makes sense. I did see some log populated in these scenarios which is confusing.
return hasLabelAndModelIdentifier(e.ObjectNew.GetLabels(), labelKey) }, DeleteFunc: func(e event.DeleteEvent) bool { return hasLabelAndModelIdentifier(e.Object.GetLabels(), labelKey) }, GenericFunc: func(e event.GenericEvent) bool { return hasLabelAndModelIdentifier(e.Object.GetLabels(), labelKey) },...
@@ -122,9 +122,12 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { Owns(&appsv1.Deployment{}). Watches(&corev1.Pod{}, &handler.EnqueueRequestForObject{}, builder.WithPredicates(podWithLabelFilter(KVCacheLabelKeyIdentifier))). Complete(r) + if err != nil {
pkg/controller/kvcache/kvcache_controller.go
26
Go
0.214
suggestion
80
51
51
false
[BUG] return directly when error occurs while adding the controller
937
vllm-project/aibrix
2,572
Go
Jeffwan
Iceber
}) if err != nil { return err } _, err = fleetInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: modelRouter.addRouteFromRayClusterFleet, DeleteFunc: modelRouter.deleteRouteFromRayClusterFleet, }) return err } type ModelRouter struct { client.Client Scheme *runtime.Scheme Run...
can we also change to the switch style to make the code consistent like we discussed in the earlier PR?
}) if err != nil { return err } _, err = fleetInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: modelRouter.addRouteFromRayClusterFleet, DeleteFunc: modelRouter.deleteRouteFromRayClusterFleet, }) return err } type ModelRouter struct { client.Client Scheme *runtime.Scheme Run...
@@ -119,7 +119,17 @@ func (m *ModelRouter) addRouteFromDeployment(obj interface{}) { } func (m *ModelRouter) deleteRouteFromDeployment(obj interface{}) { - deployment := obj.(*appsv1.Deployment)
pkg/controller/modelrouter/modelrouter_controller.go
26
Go
0.429
question
103
51
51
false
[BUG] controller: handle DeletedFinalStateUnknown by the delete func
938
vllm-project/aibrix
2,572
Go
Jeffwan
Iceber
// newReconciler returns a new reconcile.Reconciler func newReconciler(mgr manager.Manager, runtimeConfig config.RuntimeConfig) (reconcile.Reconciler, error) { reconciler := &RayClusterFleetReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor(control...
I think this is kind of typo, so changed
func newReconciler(mgr manager.Manager, runtimeConfig config.RuntimeConfig) (reconcile.Reconciler, error) { reconciler := &RayClusterFleetReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor(controllerName), Expectation: expectation.NewControllerE...
@@ -84,7 +82,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { return err } - klog.V(4).InfoS("Finished to add model-adapter-controller")
pkg/controller/rayclusterfleet/rayclusterfleet_controller.go
26
Go
0.143
nitpick
40
51
51
false
[Misc]: move crd check in Initialize part
949
vllm-project/aibrix
2,572
Go
googs1025
googs1025
) // validateStreamOptions validates whether stream options to include usage is set for user request func validateStreamOptions(requestID string, user utils.User, jsonMap map[string]interface{}) *extProcPb.ProcessingResponse { if user.Tpm != 0 { streamOptions, ok := jsonMap["stream_options"].(map[string]interface{}...
`CheckEnvExists` doesn't seem like the best name. Maybe rename it to `LookupEnv` or just use os.LookupEnv directly? https://github.com/vllm-project/aibrix/blob/6c325828b22098ef17240c7fbd50d032ce93449c/pkg/utils/redis.go#L33-L38 @Jeffwan What do you think?
) // validateStreamOptions validates whether stream options to include usage is set for user request func validateStreamOptions(requestID string, user utils.User, jsonMap map[string]interface{}) *extProcPb.ProcessingResponse { if user.Tpm != 0 { streamOptions, ok := jsonMap["stream_options"].(map[string]interface{}...
@@ -50,30 +50,20 @@ func validateStreamOptions(requestID string, user utils.User, jsonMap map[string return nil } +var defaultRoutingStrategy, defaultRoutingStrategyEnabled = utils.CheckEnvExists(EnvRoutingAlgorithm)
pkg/plugins/gateway/util.go
26
Go
0.643
question
259
51
51
false
[Bug] avoid frequent lookup of the routing strategy env
956
vllm-project/aibrix
2,572
Go
Iceber
Iceber
config, err = rest.InClusterConfig() } else { klog.Infof("using configuration from '%s'", kubeConfig) config, err = clientcmd.BuildConfigFromFlags("", kubeConfig) } if err != nil { panic(err) } cache.InitForGateway(config, stopCh, redisClient) // Connect to K8s cluster k8sClient, err := kubernetes.New...
we used `klog.Fatalf` earlier, should we keep it same?
} else { klog.Infof("using configuration from '%s'", kubeConfig) config, err = clientcmd.BuildConfigFromFlags("", kubeConfig) } if err != nil { panic(err) } cache.InitForGateway(config, stopCh, redisClient) // Connect to K8s cluster k8sClient, err := kubernetes.NewForConfig(config) if err != nil { kl...
@@ -85,10 +86,14 @@ func main() { if err != nil { klog.Fatalf("failed to listen: %v", err) } + gatewayK8sClient, err := versioned.NewForConfig(config) + if err != nil { + panic(err.Error())
cmd/plugins/main.go
26
Go
0.429
question
54
51
51
false
Add httproute status check for response header errors
957
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
func (s *Server) selectTargetPod(ctx *types.RoutingContext, pods types.PodList) (string, error) { router, err := routing.Select(ctx.Algorithm)(ctx) if err != nil { return "", err } if pods.Len() == 0 { return "", fmt.Errorf("no pods to forward request") } readyPods := utils.FilterRoutablePods(pods.All()) i...
why does this method return a string? does error look better? the caller can use error.Error() to wrap the message, otherwise, for validated scenarios, it need to check string == ""? I feel change to error type as return result is better
} func (s *Server) selectTargetPod(ctx *types.RoutingContext, pods types.PodList) (string, error) { router, err := routing.Select(ctx.Algorithm)(ctx) if err != nil { return "", err } if pods.Len() == 0 { return "", fmt.Errorf("no pods to forward request") } readyPods := utils.FilterRoutablePods(pods.All()) ...
@@ -156,6 +167,48 @@ func (s *Server) selectTargetPod(ctx *types.RoutingContext, pods types.PodList) return router.Route(ctx, &utils.PodArray{Pods: readyPods}) } +// validateHTTPRouteStatus checks if httproute object exists and validates its conditions are true +func (s *Server) validateHTTPRouteStatus(ctx context...
pkg/plugins/gateway/gateway.go
26
Go
0.643
question
242
51
51
false
Add httproute status check for response header errors
957
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
"k8s.io/client-go/kubernetes" "k8s.io/klog/v2" extProcPb "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" envoyTypePb "github.com/envoyproxy/go-control-plane/envoy/type/v3" "github.com/vllm-project/aibrix/pkg/cache" routing "github.com/vllm-project/aibrix/pkg/plugins/gateway/algorithms" "githu...
Does this gateway client have caching enabled? From what I see, it should be safe now since httproute fetch is only triggered on errors. I just want to confirm that it won’t cause issues for the API server in misconfigured scenarios—e.g., if a large number of requests are sent directly to the API server.
"google.golang.org/grpc/codes" "google.golang.org/grpc/status" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" extProcPb "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" envoyTypePb "github.com/envoyproxy/go-control-plane/envoy/type/v3" "github.com/vllm-project/aibrix/pkg/cache" routing "githu...
@@ -38,17 +37,25 @@ import ( "github.com/vllm-project/aibrix/pkg/types" "github.com/vllm-project/aibrix/pkg/utils" healthPb "google.golang.org/grpc/health/grpc_health_v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayapi "sigs.k8s.io/gateway-api/pkg/client/...
pkg/plugins/gateway/gateway.go
26
Go
0.643
question
305
51
51
false
Add httproute status check for response header errors
957
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
return "", fmt.Errorf("no ready pods available for fallback") } if len(readyPods) == 1 { for _, pod := range readyPods { ctx.SetTargetPod(pod) return ctx.TargetAddress(), nil } } return router.Route(ctx, &utils.PodArray{Pods: readyPods}) } // validateHTTPRouteStatus checks if httproute object exists a...
In our current setting, there's only one parent right? there's no need to check all parents so break here is safe
if len(readyPods) == 0 { return "", fmt.Errorf("no ready pods available for fallback") } if len(readyPods) == 1 { for _, pod := range readyPods { ctx.SetTargetPod(pod) return ctx.TargetAddress(), nil } } return router.Route(ctx, &utils.PodArray{Pods: readyPods}) } // validateHTTPRouteStatus checks if...
@@ -156,6 +167,48 @@ func (s *Server) selectTargetPod(ctx *types.RoutingContext, pods types.PodList) return router.Route(ctx, &utils.PodArray{Pods: readyPods}) } +// validateHTTPRouteStatus checks if httproute object exists and validates its conditions are true +func (s *Server) validateHTTPRouteStatus(ctx context...
pkg/plugins/gateway/gateway.go
26
Go
0.357
suggestion
113
51
51
false
Add httproute status check for response header errors
957
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
} else { klog.Infof("using configuration from '%s'", kubeConfig) config, err = clientcmd.BuildConfigFromFlags("", kubeConfig) } if err != nil { panic(err) } cache.InitForGateway(config, stopCh, redisClient) // Connect to K8s cluster k8sClient, err := kubernetes.NewForConfig(config) if err != nil { kl...
this server automatically implements `Check` and `Watch` so we do not need maintain healthcheck server ourselves?
klog.Infof("using configuration from '%s'", kubeConfig) config, err = clientcmd.BuildConfigFromFlags("", kubeConfig) } if err != nil { panic(err) } cache.InitForGateway(config, stopCh, redisClient) // Connect to K8s cluster k8sClient, err := kubernetes.NewForConfig(config) if err != nil { klog.Fatalf(...
@@ -87,9 +86,11 @@ func main() { } s := grpc.NewServer() - extProcPb.RegisterExternalProcessorServer(s, gateway.NewServer(redisClient, k8sClient)) - healthPb.RegisterHealthServer(s, gateway.NewHealthCheckServer()) + + healthCheck := health.NewServer()
cmd/plugins/main.go
26
Go
0.5
question
118
51
51
false
Add graceful shutdown for gateway and add liveness/readiness probes
962
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
return errors.New("certificates are not ready") } }); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } } // TODO: if...
Looking at the code, I don't think the order will have any particular effect. Let me know if I'm overlooking something.
return mgr.GetWebhookServer().StartedChecker()(req) default: return errors.New("webhook certificates are not ready") } }); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { set...
@@ -290,13 +301,20 @@ func main() { } // TODO: if the argument list will grow, we should create a ControllerSetupOptions struct instead. -func setupControllers(mgr ctrl.Manager, runtimeConfig config.RuntimeConfig, certsReady chan struct{}, disableWebhook bool) { +func setupControllers(mgr ctrl.Manager, runtimeConfi...
cmd/controllers/main.go
26
Go
0.357
suggestion
122
39
40
false
cmd/controllers: add readyz check for the webhook
969
vllm-project/aibrix
2,572
Go
Iceber
Iceber
os.Exit(1) } setupLog.Info("starting cache") stopCh := make(chan struct{}) defer close(stopCh) var config *rest.Config // ref: https://github.com/kubernetes-sigs/controller-runtime/issues/878#issuecomment-1002204308 kubeConfig := flag.Lookup("kubeconfig").Value.String() if kubeConfig == "" { setupLog.Info...
Let's revert this, we'll make sure the certsReady will always be closed.
os.Exit(1) } setupLog.Info("starting cache") stopCh := make(chan struct{}) defer close(stopCh) var config *rest.Config // ref: https://github.com/kubernetes-sigs/controller-runtime/issues/878#issuecomment-1002204308 kubeConfig := flag.Lookup("kubeconfig").Value.String() if kubeConfig == "" { setupLog.Info...
@@ -248,12 +250,11 @@ func main() { cache.Init(config, stopCh) } - certsReady := make(chan struct{})
cmd/controllers/main.go
26
Go
0.214
suggestion
72
51
51
false
cmd/controllers: add readyz check for the webhook
969
vllm-project/aibrix
2,572
Go
kerthcet
Iceber
return nil } select { case <-certsReady: return mgr.GetWebhookServer().StartedChecker()(req) default: return errors.New("certificates are not ready") } }); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } setupLog.Info("starting manager") if err := mgr.Start(ctr...
Basically, certsReady doesn't mean disableWebhook, which will lead to confusion for further readers, let's not do like this. But we can remove the disableWebhook judgement here because once `disabledWebhook=false`, the certsReady will always be closed.
if err := mgr.AddReadyzCheck("readyz", func(req *http.Request) error { if disableWebhook { return nil } select { case <-certsReady: return mgr.GetWebhookServer().StartedChecker()(req) default: return errors.New("webhook certificates are not ready") } }); err != nil { setupLog.Error(err, "unabl...
@@ -290,13 +301,20 @@ func main() { } // TODO: if the argument list will grow, we should create a ControllerSetupOptions struct instead. -func setupControllers(mgr ctrl.Manager, runtimeConfig config.RuntimeConfig, certsReady chan struct{}, disableWebhook bool) { +func setupControllers(mgr ctrl.Manager, runtimeConfi...
cmd/controllers/main.go
26
Go
0.643
suggestion
252
46
47
false
cmd/controllers: add readyz check for the webhook
969
vllm-project/aibrix
2,572
Go
kerthcet
Iceber
) } func validateInference(t *testing.T, modelName string) { client := createOpenAIClient(gatewayURL, apiKey) validateInferenceWithClient(t, client, modelName) } func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName string) { chatCompletion, err := client.Chat.Completions.New(context.TOD...
We set `expectedPodCount` to be the actual expected number, and using it for traversal seems to be OK, but I'm not sure if it will be confusing? 🤔
r.URL.Path = "/v1" + r.URL.Path return mn(r) }), option.WithHeader("routing-strategy", routingStrategy), option.WithMaxRetries(0), respOpt, ) } func validateInference(t *testing.T, modelName string) { client := createOpenAIClient(gatewayURL, apiKey) validateInferenceWithClient(t, client, modelName) } ...
@@ -130,3 +133,18 @@ func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName assert.NotEmpty(t, chatCompletion.Choices, "chat completion has no choices returned") assert.NotNil(t, chatCompletion.Choices[0].Message.Content, "chat completion has no message returned") } + +func validateAllPods...
test/e2e/util.go
26
Go
0.5
suggestion
148
38
43
false
E2E CI fix to ensure all pods are ready
972
vllm-project/aibrix
2,572
Go
googs1025
varungup90
/* Copyright 2024 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar...
I believe https://github.com/onsi/ginkgo is more solid here with like `Eventually` semantic.
func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName string) { chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: openai.F([]openai.ChatCompletionMessageParamUnion{ openai.UserMessage("Say this is a test"), }), Model: openai...
@@ -129,3 +132,17 @@ func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName assert.NotEmpty(t, chatCompletion.Choices, "chat completion has no choices returned") assert.NotNil(t, chatCompletion.Choices[0].Message.Content, "chat completion has no message returned") } + +func validateAllPods...
test/e2e/util.go
26
Go
0.357
suggestion
92
149
30
false
E2E CI fix to ensure all pods are ready
972
vllm-project/aibrix
2,572
Go
kerthcet
varungup90
/* Copyright 2024 The Aibrix Team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar...
i am curious we already check pod status here https://github.com/vllm-project/aibrix/blob/bc6cef162416496dd84ed6972c5eecff1fcc48a8/.github/workflows/installation-tests.yml#L142 and then run `make test-e2e`, why does it work as expected and we have to check one more time here?
option.WithMaxRetries(0), respOpt, ) } func validateInference(t *testing.T, modelName string) { client := createOpenAIClient(gatewayURL, apiKey) validateInferenceWithClient(t, client, modelName) } func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName string) { chatCompletion, err := ...
@@ -136,3 +139,17 @@ func validateInferenceWithClient(t *testing.T, client *openai.Client, modelName assert.NotEmpty(t, chatCompletion.Choices, "chat completion has no choices returned") assert.NotNil(t, chatCompletion.Choices[0].Message.Content, "chat completion has no message returned") } + +func validateAllPods...
test/e2e/util.go
26
Go
0.571
question
278
139
39
false
E2E CI fix to ensure all pods are ready
972
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
nodeType = "ray.io/node-type" nodeWorker = "worker" ) func initCacheInformers(instance *Store, config *rest.Config, stopCh <-chan struct{}) error { if err := v1alpha1scheme.AddToScheme(scheme.Scheme); err != nil { return err } k8sClientSet, err := kubernetes.NewForConfig(config) if err != nil { ...
HandleCrash is usually used in goroutinue or in functions that contain functions that are not sure whether a panic will occur or not. it doesn't seem necessary in here.
nodeWorker = "worker" ) func initCacheInformers(instance *Store, config *rest.Config, stopCh <-chan struct{}) error { if err := v1alpha1scheme.AddToScheme(scheme.Scheme); err != nil { return err } k8sClientSet, err := kubernetes.NewForConfig(config) if err != nil { return err } crdClientSet, err := v...
@@ -59,16 +58,6 @@ func initCacheInformers(instance *Store, config *rest.Config, stopCh <-chan stru crdFactory := crdinformers.NewSharedInformerFactoryWithOptions(crdClientSet, 0) podInformer := factory.Core().V1().Pods().Informer() - modelInformer := crdFactory.Model().V1alpha1().ModelAdapters().Informer() - - d...
pkg/cache/informers.go
26
Go
0.571
bug
171
51
51
false
[BUG] cache: start informer after adding the resource handler
981
vllm-project/aibrix
2,572
Go
Iceber
Iceber
import logging import os import threading from typing import Dict, Optional, Tuple import redis import uvicorn from kubernetes import client, config, watch from starlette.applications import Starlette from starlette.responses import JSONResponse, PlainTextResponse from aibrix.gpu_optimizer.load_monitor.load_reader im...
@weapons97 could you help format this file. seems the linter report the format issue on this file
import logging import os import threading from typing import Dict, Optional, Tuple import redis import uvicorn from kubernetes import client, config, watch from starlette.applications import Starlette from starlette.responses import JSONResponse, PlainTextResponse from aibrix.gpu_optimizer.load_monitor.load_reader im...
@@ -35,6 +35,7 @@ MIN_REPLICAS_LABEL = "model.aibrix.ai/min_replicas" REDIS_HOST = os.getenv("REDIS_HOST", "localhost") REDIS_PORT = int(os.getenv("REDIS_PORT", 6379)) +REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", None)
python/aibrix/aibrix/gpu_optimizer/app.py
26
Python
0.286
style
97
51
51
false
Update add redis pass for client
990
vllm-project/aibrix
2,572
Go
Jeffwan
weapons97
// mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(numbers ...
We may have fallback in different routing algorithms. We can extract a method and indicate the use of this fallback method.
) // mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(number...
@@ -39,3 +45,16 @@ func standardDeviation(numbers []float64) float64 { variance := sumOfSquares / float64(len(numbers)-1) return math.Sqrt(variance) } + +// SelectRandomPodAsFallback selects a pod randomly as a fallback. +// This method should only be used when all other selection mechanisms have failed. +// For e...
pkg/plugins/gateway/algorithms/util.go
26
Go
0.429
refactor
123
34
36
false
[Misc] fix: Optimizing Route method of the gateway algorithms
1,001
vllm-project/aibrix
2,572
Go
googs1025
googs1025
) func init() { RegisterDelayedConstructor(RouterLeastBusyTime, NewLeastBusyTimeRouter) } type leastBusyTimeRouter struct { cache cache.Cache } func NewLeastBusyTimeRouter() (types.Router, error) { c, err := cache.Get() if err != nil { return nil, err } return leastBusyTimeRouter{ cache: c, }, nil } fun...
ip check at line 57 can be removed. FilterRoutablePods already does it. Please remove this at other places if present.
) func init() { RegisterDelayedConstructor(RouterLeastBusyTime, NewLeastBusyTimeRouter) } type leastBusyTimeRouter struct { cache cache.Cache } func NewLeastBusyTimeRouter() (types.Router, error) { c, err := cache.Get() if err != nil { return nil, err } return leastBusyTimeRouter{ cache: c, }, nil } fun...
@@ -51,15 +49,11 @@ func NewLeastBusyTimeRouter() (types.Router, error) { }, nil } -func (r leastBusyTimeRouter) Route(ctx *types.RoutingContext, pods types.PodList) (string, error) { +func (r leastBusyTimeRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error) { var targetPod *v1.Po...
pkg/plugins/gateway/algorithms/least_busy_time.go
26
Go
0.429
refactor
119
51
51
false
[Misc] fix: Optimizing Route method of the gateway algorithms
1,001
vllm-project/aibrix
2,572
Go
varungup90
googs1025
// mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(numbers ...
Pass the routing context as argument and use ctx.requestID in the log for ln 54 and 57.
) // mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(number...
@@ -39,3 +45,16 @@ func standardDeviation(numbers []float64) float64 { variance := sumOfSquares / float64(len(numbers)-1) return math.Sqrt(variance) } + +// SelectRandomPodAsFallback selects a pod randomly as a fallback. +// This method should only be used when all other selection mechanisms have failed. +// For e...
pkg/plugins/gateway/algorithms/util.go
26
Go
0.286
suggestion
87
34
36
false
[Misc] fix: Optimizing Route method of the gateway algorithms
1,001
vllm-project/aibrix
2,572
Go
varungup90
googs1025
// mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(numbers [...
You can do a warn log message here. And remove the warn message individually from caller just after if targetPod == nil check, this warn message does not have requestID so it is not useful eitherwise.
// mean calculates the mean of a slice of float64 numbers. func mean(numbers []float64) float64 { sum := 0.0 for _, number := range numbers { sum += number } return sum / float64(len(numbers)) } // standardDeviation calculates the standard deviation of a slice of float64 numbers. func standardDeviation(numbers [...
@@ -39,3 +46,17 @@ func standardDeviation(numbers []float64) float64 { variance := sumOfSquares / float64(len(numbers)-1) return math.Sqrt(variance) } + +// SelectRandomPodAsFallback selects a pod randomly as a fallback. +// This method should only be used when all other selection mechanisms have failed. +// For e...
pkg/plugins/gateway/algorithms/util.go
26
Go
0.5
suggestion
201
34
34
false
[Misc] fix: Optimizing Route method of the gateway algorithms
1,001
vllm-project/aibrix
2,572
Go
varungup90
googs1025