Last of four; stacked on #38048. The record is the operator's input; the bags are what is in effect. A reader that takes the record and reads a field off it gets the input, which is the wrong one of the two whenever resolution decided something -- and the mistake is silent, because for most fields and most launches the two agree. Several of these files already read both ways, sometimes in the same expression: ```python get_tokenizer( get_serving().tokenizer_path, tokenizer_mode=server_args.tokenizer_mode, # the input, not the decision ... ) ``` Sixty-odd files convert. Record field reads in runtime code go from 199 to 11. Nine parameters that the conversion emptied are dropped along with the argument at every call site -- the dead-parameter ratchet is what names them. ### "Runs after its process publishes" is a per-entry-point claim Most converted reads sit in the serving and model-executor layers, which only exist after publication, or in the two subprocess entry points, which publish first thing. Three places are not like that, and they keep reading the record they were handed: - **`HttpServerEngineAdapter`** launches the server as a *child*. The parent resolves the record and never publishes, so the adapter's own reads -- the launch banner, the API key in its readiness loop, the TP width in `update_weights_from_tensor` -- are of `self.server_args`. A bag read here fails closed in a bare process, or answers for an unrelated engine in one that happens to have published. - **`serve_grpc`** reads its sidecar port before the integrated servicer builds the `Engine` that publishes. The comment above that line already said so and already bound `cfg = resolving_view(server_args)` for it; the sidecar port and the port it derives from read `cfg`. - **`initialize_dp_attention`** runs from callers whose publish is not guaranteed, so its one predicate stays on the resolution view. `ROLE_NAMESPACE_SETS["dp_controller"]` gains `observability` and `serving`, because the controller's metrics gate, tracing setup and worker-port broadcast now read those namespaces. Under `SGLANG_ROLE_NAMESPACES=enforce` that set is what the process may read, so a conversion that reaches a new namespace has to widen it in the same change. ## Three things worth a reviewer's attention **Eleven reads were `getattr(record, "field", default)`.** An AST scan for attribute access does not see those, so the census that said "43 readers" was counting the shape it could match rather than the thing it was after. `incremental_streaming_output` was read that way twice, and the transcription tests were the only reason it surfaced. **Not every record read is a bag read waiting to happen.** A multimodal processor's `base_gpu_id` is the instance's, not the process's: two engines in one process keep different ones, and `test_publishing_another_config_does_not_move_the_device` exists to say so. It stays on the record while `rl_on_policy_target` beside it moves. `RequestMetricsExporter` is the same shape -- it is handed the directory it writes to, and a test builds several with different ones. `configure_logger` is a third: 17 call sites, one of which passes an `argparse.Namespace`, so it is not a global-context reader at all. Those eleven remaining reads are the ones with a reason. **The fixtures move with the code.** Tests that hung config off a mock manager now publish a record, which is what the serving layer reads; where a test states a value it says so with `override_server_args` instead of assigning through the mock. `test_hisparse_unit` is the last of them: it stubbed a `server_args` onto a fake scheduler to say the decode radix cache was off, and the value it was standing in for is the published default, so the stub goes and the class publishes. ## Two things CI caught that a local sweep could not **`unittest.TestCase.enterContext` is Python 3.11+.** The converted fixtures used it at 18 sites; `requires-python` is `>=3.10` and CI runs 3.10, so every one of them raised `AttributeError` there while passing on a newer local interpreter. They call `enter_override(self, ...)` now -- a four-line helper in `sglang/test/test_utils.py` over the override's own `install()` / `restore()`. **A batched sweep cannot see a missing publish.** Three fixtures needed a published config and did not have one; each *passed* inside a shard where some other file had published, and failed when run alone. The affected cases are `test_serving_completions` (which set `incremental_streaming_output` on the mock manager's record, where nothing reads it now), `test_qwen3_vl_feature_materialization` (same shape for `mm_enable_dp_encoder`), and the two Qwen Rust tests -- whose fixture already carried the comment `# Non-auto: get_resolved_model_impl would choke on a SimpleNamespace` next to the `model_impl` it sets, which is exactly what happened once `get_mm_processor_cls` started reading that value from the bag. Its `publish` mirrors `model_impl` now, like the four fields it already mirrored. ## Verification A full registered-unit sweep (648 files) against this stack's merge-base: 19 failures on both sides, the same 19, none of them config. That sweep is what caught 23 failures the file-scoped runs missed -- and, later, that the narrower 139-file list did not even contain the files this change reaches. It is also what caught the `test_hisparse_unit` fixture above: the file passes inside a shard where something else published, and fails when it is run on its own, which is why every failing file is re-run alone before it is counted.
178 lines
5.8 KiB
Python
178 lines
5.8 KiB
Python
"""Stub CUDA-only deps before importing sglang.srt serving modules. Must
|
|
be imported first by every /v1/responses test that runs on CPU."""
|
|
|
|
try:
|
|
import torch
|
|
|
|
_ORIGINAL_TORCH_COMPILE = torch.compile
|
|
|
|
def _identity_compile(fn=None, **kwargs):
|
|
if fn is None:
|
|
return lambda inner_fn: inner_fn
|
|
return fn
|
|
|
|
torch.compile = _identity_compile
|
|
except ImportError:
|
|
torch = None
|
|
_ORIGINAL_TORCH_COMPILE = None
|
|
|
|
from sglang.test.test_utils import maybe_stub_sgl_kernel
|
|
|
|
maybe_stub_sgl_kernel()
|
|
|
|
import asyncio
|
|
import json
|
|
from typing import AsyncIterator
|
|
from unittest.mock import Mock
|
|
|
|
from sglang.srt.entrypoints.openai.protocol import RequestResponseMetadata
|
|
from sglang.srt.entrypoints.openai.serving_responses import OpenAIServingResponses
|
|
from sglang.srt.runtime_context import get_context, publish
|
|
from sglang.srt.server_args import ServerArgs
|
|
from sglang.test.ci.ci_register import register_cpu_ci
|
|
|
|
register_cpu_ci(
|
|
est_time=0,
|
|
suite="base-a-test-cpu",
|
|
disabled="helper module — exported fixtures, not a test",
|
|
)
|
|
|
|
if torch is not None:
|
|
torch.compile = _ORIGINAL_TORCH_COMPILE
|
|
|
|
|
|
class MockTokenizerManager:
|
|
def __init__(self, *, is_multimodal: bool = False):
|
|
self.model_config = Mock(is_multimodal=is_multimodal, context_len=4096)
|
|
self.model_config.get_default_sampling_params.return_value = {}
|
|
self.model_config.hf_config = Mock(
|
|
model_type="llama", architectures=["LlamaForCausalLM"]
|
|
)
|
|
self.server_args = Mock(
|
|
enable_cache_report=False,
|
|
reasoning_parser=None,
|
|
stream_response_default_include_usage=False,
|
|
tokenizer_metrics_allowed_custom_labels=None,
|
|
tool_call_parser=None,
|
|
incremental_streaming_output=False,
|
|
)
|
|
# Stands in for the context's resolved leaves: an override replaces the
|
|
# field's one live value, the seed stays on server_args.
|
|
self._config_overrides = {}
|
|
self.tokenizer = Mock()
|
|
self.tokenizer.encode.return_value = [1, 2, 3]
|
|
self.tokenizer.chat_template = None
|
|
self.tokenizer.bos_token_id = 1
|
|
self.num_reserved_tokens = 0
|
|
self.generate_request = Mock()
|
|
self.create_abort_task = Mock()
|
|
|
|
def config_value(self, name: str):
|
|
"""The value in effect for one config field."""
|
|
if name in self._config_overrides:
|
|
return self._config_overrides[name]
|
|
return getattr(self.server_args, name)
|
|
|
|
|
|
class MockTemplateManager:
|
|
def __init__(self):
|
|
self.chat_template_name = "llama-3"
|
|
self.jinja_template_content_format = None
|
|
self.completion_template_name = None
|
|
self.reasoning_config = None
|
|
self.force_reasoning = False
|
|
self.jinja_template_may_reorder_tool_results = False
|
|
|
|
|
|
def make_serving(*, is_multimodal: bool = False) -> OpenAIServingResponses:
|
|
"""The serving layer reads its config from the bags, so the fixture
|
|
publishes one. Idempotent: a caller that already published keeps its own,
|
|
which is how a test states a value the default record does not carry."""
|
|
if not get_context().is_config_namespace_published("serving"):
|
|
publish(ServerArgs(model_path="dummy"), role="tokenizer")
|
|
return OpenAIServingResponses(
|
|
MockTokenizerManager(is_multimodal=is_multimodal), MockTemplateManager()
|
|
)
|
|
|
|
|
|
async def collect_stream_events(stream: AsyncIterator[str]) -> list[str]:
|
|
events = []
|
|
async for chunk in stream:
|
|
events.append(chunk)
|
|
return events
|
|
|
|
|
|
def event_types(events: list[str]) -> list[str]:
|
|
return [
|
|
line[len("event: ") :].strip()
|
|
for chunk in events
|
|
for line in chunk.splitlines()
|
|
if line.startswith("event: ")
|
|
]
|
|
|
|
|
|
def event_payloads(events: list[str]) -> list[dict]:
|
|
return [
|
|
json.loads(line[len("data: ") :])
|
|
for chunk in events
|
|
for line in chunk.splitlines()
|
|
if line.startswith("data: ")
|
|
]
|
|
|
|
|
|
def find_completed_event(events: list[str]) -> dict:
|
|
for chunk in events:
|
|
lines = chunk.splitlines()
|
|
if lines and lines[0] == "event: response.completed":
|
|
return json.loads(lines[1][len("data: ") :])
|
|
raise AssertionError("response.completed event missing from stream")
|
|
|
|
|
|
def engine_chunk(text, completion_tokens=1, *, finish=False):
|
|
return {
|
|
"text": text,
|
|
"meta_info": {
|
|
"id": "rid",
|
|
"prompt_tokens": 5,
|
|
"completion_tokens": completion_tokens,
|
|
"cached_tokens": 0,
|
|
"reasoning_tokens": 0,
|
|
"finish_reason": {"type": "stop"} if finish else None,
|
|
},
|
|
}
|
|
|
|
|
|
class StreamFixture:
|
|
"""Drives ``responses_stream_generator_non_harmony`` over a chunk list."""
|
|
|
|
def __init__(self, serving, request, *, require_reasoning=False):
|
|
self.serving = serving
|
|
self.request = request
|
|
self.require_reasoning = require_reasoning
|
|
self.request_metadata = RequestResponseMetadata(request_id=request.request_id)
|
|
|
|
def run(self, chunks) -> list[str]:
|
|
async def gen():
|
|
for ch in chunks:
|
|
yield ch
|
|
|
|
async def collect():
|
|
return await collect_stream_events(
|
|
self.serving.responses_stream_generator_non_harmony(
|
|
self.request,
|
|
sampling_params={},
|
|
result_generator=gen(),
|
|
model_name="x",
|
|
tokenizer=Mock(),
|
|
request_metadata=self.request_metadata,
|
|
require_reasoning=self.require_reasoning,
|
|
)
|
|
)
|
|
|
|
return asyncio.run(collect())
|
|
|
|
def run_seq(self, chunks) -> list[tuple]:
|
|
"""``run`` plus (event type, payload) pairing, the common assertion shape."""
|
|
events = self.run(chunks)
|
|
return list(zip(event_types(events), event_payloads(events)))
|