Skip to content

serve: register /completion, the path the short and spec warm-ups post to (Fixes #2853) - #2855

Merged
bong-water-water-bong merged 1 commit into
mainfrom
fix/2853-completion-route
Nov 17, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
fix/2853-completion-route

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2853.

What was wrong

1bit serve registered two completion routes, and the short and the spec warm-up posted to a third:

srv.Post("/v1/chat/completions", post);
srv.Post("/v1/completions", post);
...
if (want_short) out.push_back(json{ { "path", "/completion" },  { "body", warmup_short_body() } });   // 404
if (want_spec)  out.push_back(json{ { "path", "/completion" },  { "body", warmup_spec_body() } });    // 404

So two of the three warm-ups moved nothing, while docs/serve.md promises the short one ("a 16-token /completion request does not…"). A warm-up is a POST the server makes to itself — no client sees the 404 and nothing in the suite asserted the route existed.

The fix, and why this shape

/completion is registered beside /v1/completions, in both route blocks (the serve table and the second one below it):

srv.Post("/completion", post);   // llama.cpp's own path for the same handler

That is the file's own convention, not a new one: /embeddings is registered beside /v1/embeddings and /rerank beside /v1/rerank. It is also what the warm-up bodies were written for — they use llama.cpp's field names (n_predict, cache_prompt) — so pointing them at /v1/completions instead would have been the smaller diff and the wrong decision: it would leave a llama.cpp client that posts to /completion still 404ing, when the two lines above already show this server intends to be usable from that side.

The arm

tools/ci/serve_routes_check.py, static on purpose: the route table and the warm-up list are two literals in one file, and the failure is their disagreement. It parses srv.Post("<path>" registrations and { "path", "<path>" } warm-up entries and requires the second set to be a subset of the first.

before: serve_routes: warm-up posts to /completion, which app/serve.cpp never registers
        (routes: /v1/chat/completions, /v1/completions, /v1/embeddings, /embeddings, /v1/rerank, /rerank)      rc 1
after:  serve_routes: all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)         rc 0

The count says "2 requests / 1 distinct path" deliberately: the short and spec warm-ups share a path, and reporting distinct paths alone would hide one of them.

New ctest rows: serve_warmup_routes plus tool_selftest_serve_routes (three arms — a registered warm-up parses, a missing route shows as a subset failure, an empty file is not a pass). Hermetic, no device, ~0.1 s.

copyright.py --check rc 0; the three files are app/serve.cpp +10, tools/ci/serve_routes_check.py +117, CMakeLists.txt +5.

🤖 Generated with Claude Code

…t to (Fixes #2853)

The server registered /v1/chat/completions and /v1/completions; `warmup_requests()` posts the short and the
spec warm-up to /completion with llama.cpp's own field names, so both answered 404 and the warm-up that
docs/serve.md promises moved nothing. A warm-up is a POST the server makes to itself, so the 404 was invisible:
no client sees it and no test asserted it.

The fix follows the file's own convention rather than inventing one: /embeddings is registered beside
/v1/embeddings and /rerank beside /v1/rerank, and /completion is llama.cpp's path for the same handler, which
is what the warm-up bodies were written for. Registered in both route blocks (the serve table and the second
one below it), so the alias holds wherever the handler is mounted.

`tools/ci/serve_routes_check.py` is the arm, and it is static on purpose: the route table and the warm-up list
are two literals in one file and the failure is their disagreement. It parses `srv.Post("<path>"` registrations
and `{ "path", "<path>" }` warm-up entries and requires the second set to be a subset of the first.

  before: serve_routes: warm-up posts to /completion, which app/serve.cpp never registers
          (routes: /v1/chat/completions, /v1/completions, /v1/embeddings, /embeddings, /v1/rerank, /rerank)   rc 1
  after:  serve_routes: all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)      rc 0

New ctest rows: `serve_warmup_routes` (the check) and `tool_selftest_serve_routes` (its three arms: a registered
warm-up parses, a missing route shows as a subset failure, an empty file is not a pass).
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2853 - Partially compliant

Compliant requirements:

  • Register /completion as an alias of the existing post handler in both server route blocks
  • Update tools/ci/serve_routes_check.py to validate that all warm-up paths are registered
  • The short and spec warm-ups now post to registered routes instead of 404ing

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Missing Route Registration

The /completion route was not registered, causing the short and spec warm-up requests to 404. This meant that the warm-ups promised to move nothing, as documented in docs/serve.md. The fix registers /completion as an alias of the existing post handler, aligning with the convention used for /embeddings and /rerank.

// llama.cpp's own path for the same handler, exactly as /embeddings and /rerank are registered beside their /v1
// forms below. Two things depend on it: the short and spec warm-ups post here (engine#2853 -- they were 404ing
// against a server that never had the route, so the warm-up they promise moved nothing), and a client written
// for llama-server uses it.
srv.Post("/completion", post);
Route Validation Check

The new serve_routes_check.py script ensures that all warm-up paths in app/serve.cpp are registered routes. This prevents future regressions where warm-up requests might post to unregistered paths, which would result in 404s and ineffective warm-ups.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# 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
# 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.

"""serve_routes_check.py -- every path a warm-up posts to is a route the server registers.

engine#2853: `warmup_requests()` posted the short and the spec warm-up to `/completion`, and `1bit serve` has never
registered that path -- it registered `/v1/chat/completions` and `/v1/completions`. Both requests answered 404, so
the warm-up `docs/serve.md` promises moved nothing, and nothing in the suite could notice: a warm-up is a POST the
server itself makes, so a wrong path is a 404 nobody reads.

The check is static on purpose: the route table and the warm-up list are two literals in one file, and the failure is
their disagreement. It parses `srv.Post("<path>"` registrations and `{ "path", "<path>" }` warm-up entries out of
`app/serve.cpp` and requires the second set to be a subset of the first.

Exit: 0 every warm-up path is registered, 1 one is not (named), 77 the file or a literal could not be read.
"""

import pathlib
import re
import sys

SOURCE = pathlib.Path("app/serve.cpp")
ROUTE = re.compile(r'srv\.Post\(\s*"([^"]+)"')
WARMUP = re.compile(r'\{\s*"path"\s*,\s*"([^"]+)"')


def routes_and_warmups(text):
    """(registered paths, warm-up paths), each in file order and de-duplicated."""
    def uniq(seq):
        seen, out = set(), []
        for s in seq:
            if s not in seen:
                seen.add(s)
                out.append(s)
        return out
    return uniq(ROUTE.findall(text)), uniq(WARMUP.findall(text))


def check(root=None):
    root = pathlib.Path(root or ".")
    path = root / SOURCE
    try:
        text = path.read_text(errors="replace")
    except OSError:
        print(f"serve_routes: cannot read {path}", file=sys.stderr)
        return 77
    routes, warmups = routes_and_warmups(text)
    requests = len(WARMUP.findall(text))   # the postings, not the distinct paths: two requests can share one
    if not routes or not warmups:
        print(f"serve_routes: {path} has {len(routes)} route(s) and {len(warmups)} warm-up path(s): one of the two "
              f"literals moved, so this check is looking at nothing", file=sys.stderr)
        return 77
    missing = [w for w in warmups if w not in routes]
    for w in missing:
        print(f"serve_routes: warm-up posts to {w}, which {path} never registers "
              f"(routes: {', '.join(routes)})")
    if missing:
        print(f"serve_routes: {len(missing)} of {len(warmups)} distinct warm-up path(s) have no route -- the request "
              f"404s and the warm-up moves nothing (engine#2853)")
        return 1
    print(f"serve_routes: all {requests} warm-up request(s) post to registered routes "
          f"({len(warmups)} distinct path(s), {len(routes)} routes)")
    return 0


def self_test():
    fails = 0

    def arm(name, ok, detail=""):
        nonlocal fails
        print(f"{'ok  ' if ok else 'FAIL'} {name}" + (f": {detail}" if detail and not ok else ""))
        fails += 0 if ok else 1

    good = '''srv.Post("/v1/chat/completions", post);
srv.Post("/v1/completions", post);
srv.Post("/completion", post);
out.push_back(json{ { "path", "/v1/chat/completions" } });
out.push_back(json{ { "path", "/completion" } });'''
    bad = '''srv.Post("/v1/chat/completions", post);
srv.Post("/v1/completions", post);
out.push_back(json{ { "path", "/v1/chat/completions" } });
out.push_back(json{ { "path", "/completion" } });'''
    r, w = routes_and_warmups(good)
    arm("a warm-up whose route exists parses", r == ["/v1/chat/completions", "/v1/completions", "/completion"] and
        w == ["/v1/chat/completions", "/completion"])
    r, w = routes_and_warmups(bad)
    arm("... and the missing route is visible as a subset failure", [x for x in w if x not in r] == ["/completion"])
    arm("no routes parses as nothing", routes_and_warmups("nothing here") == ([], []))
    print(f"serve_routes: {'ok' if not fails else f'{fails} failed'}")
    return 0 if not fails else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    if len(argv) > 1 and argv[1] in ("-h", "--help"):
        print("usage: serve_routes_check.py [--self-test] [ROOT]")
        print("Fails when a warm-up in app/serve.cpp posts to a path that file never registers.")
        return 0
    return check(argv[1] if len(argv) > 1 else None)


if __name__ == "__main__":
    sys.exit(main(sys.argv))

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 176dfb2: CHANGES

This is #2854's fix with a different checker, and neither PR touches the half that costs the time: the warm-up bodies still send n_predict, which this parser does not read.

warmup_short_body():  { "prompt": …, "n_predict": 0, "cache_prompt": false }
warmup_spec_body():   body["n_predict"] = 2;
forward_serve.cpp:348: max_tokens = int_field(body, "max_completion_tokens", int_field(body, "max_tokens", 256));

n_predict is read nowhere in app/ or npu/ (grep: only the two warm-up builders), and npu::options_from_body guards each key with if (body.contains(…)), so an unknown key is silently ignored rather than refused. After this PR the warm-ups stop 404ing and start decoding up to 256 tokens each instead of 0 and 2 — on a 27B the code's own comment prices one such step at 10.4 s. Before: cheap and useless. After: expensive and the wrong shape.

Fix, one of:

  • send max_tokens (0 / 2) from the body builders, or
  • honour n_predict in forward_serve.cpp's parser — the route is llama.cpp-shaped, so this is the coherent one, and it makes the warm-up's own naming truthful.

The duplicate, which is the merge-order decision

#2854 does the same thing (registers /completion in both servers, adds a source-only checker) and additionally adds failed/sent accounting with a warm-up INCOMPLETE -- %d of %d request(s) failed … line — which is how the original 404s sat in the log unnoticed, one stderr line per warm-up. This PR's checker is the cleaner of the two interfaces (positional root, 117 lines, 3 arms) and it is load-bearing: deleting both srv.Post("/completion", post) lines gives

serve_routes: warm-up posts to /completion, which …/app/serve.cpp never registers (routes: /v1/chat/completions, /v1/completions, /v1/embeddings, /embeddings, /v1/rerank, /rerank)
serve_routes: 1 of 1 distinct warm-up path(s) have no route -- the request 404s and the warm-up moves nothing (engine#2853)

So: one of #2854 / #2855 should close, and whichever survives should carry this PR's checker interface and #2854's INCOMPLETE accounting, plus the field-name fix above.

What is right

  • Registering /completion in both servers (serve_models and serve_child) rather than one, with the comment noting it sits beside /v1/completions exactly as /embeddings and /rerank do — so the route table stays coherent per server.
  • The reason a test was needed at all is stated precisely: "no test could see them because a warm-up is a POST the server makes to itself" — a self-request is invisible to any row that only exercises client-facing paths.
  • The checker reads the two literals from one file (the route table and the warm-up list in app/serve.cpp), so it cannot drift from what it checks, and its subset phrasing is the right predicate: every warm-up path must be among the registered routes.

@bong-water-water-bong
bong-water-water-bong merged commit f15525d into main Nov 17, 2026
12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the fix/2853-completion-route branch November 17, 2026 18:05
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…id not carry) (#2883)

The two warm-ups that posted to "/completion" while this server served only
/v1/* warmed nothing, and the only trace was one stderr line per request. #2855
registered the route; nothing yet keeps the two lists in step, so the next
rename can orphan a warm-up the same way.

Source-only: parses the literals in warmup_requests() and the paths handed to
srv.Get/srv.Post, matches regex registrations as regexes, and exits 1 on a
warm-up path with no registration, 2 when its own parser is out of date.

  origin/main           rc 0  every warm-up path is a registered route
  d110d59 (pre-#2855)   rc 1  NOT REGISTERED: warm-up posts to /completion
  --self-test           4/4 arms

Refs #2853

Co-authored-by: pi-os3 <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…stead of 256 (Fixes #2884) (#2887)

#2855 registered `/completion` -- llama.cpp's route -- for the two warm-ups, and they still did nothing useful
because their bodies speak llama.cpp while the parser speaks OpenAI: `warmup_short_body()` sets `n_predict: 0` and
`warmup_spec_body()` `n_predict: 2`, and `forward_serve.cpp` read only `max_completion_tokens`/`max_tokens`, so both
kept the default `max_tokens = 256` and answered 200. The "spec" warm-up -- whose whole purpose is to pay a 5.6 GB
host-copy step with a two-token request (the comment above it) -- was running a 256-token generation instead.

The alias goes where the other limit fields are read, OpenAI first so nothing that works today moves:

    max_completion_tokens -> n_predict -> max_tokens -> 256

`n_predict` and not "fix the two builders", because `/completion` is llama.cpp's own path and a client written for
llama-server posts `n_predict`: correcting only the warm-ups would leave the route lying to the dialect it now serves.

`tools/ci/serve_routes_check.py` grows the body half the issue asks for, and it compares PER BUILDER, not the union --
a union hides this bug, because the chat warm-up sets `max_tokens` and makes the intersection non-empty:

  main's parser:  warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens
                  warmup_spec_body()  sets n_predict, …
                  serve_routes: 2 warm-up body builder(s) set a token limit the parser never reads        rc 1
  with the fix:   every warm-up body's token limit is read by the parser (3 builder(s), … n_predict)      rc 0

`--self-test` still ok; `copyright.py --check` rc 0. What this does NOT prove: that the requests now really send 0 and
2 tokens on a live server — the arm is static, and the runtime proof is a `serve` run with the warm-up log, which
needs a model and a ticket.

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…o serve_routes_check.py (#2891)

* ci: one warm-up check, not two — the route regex and srv.Get move into serve_routes_check.py (engine#2853, #2884)

`main` runs two checks for the same property. `serve_routes_check.py` arrived with the fix in #2855 and now carries
both halves (engine#2853's paths, engine#2884's token-limit fields); `warmup_route_check.py` arrived in #2883 and
checked the route half a second time, with one capability the first lacked: it parses `R"(...)"` raw-string
registrations and matches them as regexes, and it sees `srv.Get` as well as `srv.Post`.

Keeping both means a change to `warmup_requests()` has to satisfy two baselines that nobody keeps in step, and a
reviewer cannot tell which is authoritative. So the two capabilities move here, with arms, and the second file and
its ctest row are deleted:

  ok   a raw-string route registration parses
  ok   a srv.Get route counts too
  ok   a regex route covers a warm-up path

`route_covers()` is the module-level predicate both the check and the arms use: a warm-up path is covered when it
equals a literal route or full-matches a regex one, and an invalid regex route is skipped rather than trusted.

Measured, on this tree and on a mutant:

  $ python3 tools/ci/serve_routes_check.py .            # 14 routes now, srv.Get included
  serve_routes: every warm-up body's token limit is read by the parser (3 builder(s), ...)
  rc=0

  $ <app/serve.cpp with the two srv.Post("/completion", post); lines deleted>
  serve_routes: warm-up posts to /completion, which ... never registers
  rc=1

The self-test is 9 arms, all green; `--self-test` and the `serve_warmup_routes` row both remain, so the property is
checked exactly as often as before, by one file.

* ci: resolve a warm-up's named constant, and refuse one this file cannot resolve (review at 7c186c1)

The review's finding was right and it is the same shape as the bug this check exists for, one level up: `WARMUP` matched
`{ "path", "<literal>" }` only, `app/serve.cpp` posts the chat warm-up as `{ "path", kWarmupPath }`, so the merged
checker verified **two of the three** warm-ups and printed `ok`. The self-test could not catch it because its fixtures
inlined the literal — a fixture easier than the artifact passes for the better reason and fails for none.

  - `WARMUP` now captures the expression and `CONST_DEF` resolves a `const char* const NAME = "..."` in the same file;
  - an identifier this file does not define is **cannot tell (77)** with its name, never a path silently skipped, so a
    future `const char* kSomething` cannot take a warm-up out of the check's view the way `kWarmupPath` did;
  - the fixtures now use the identifier form the artifact uses, plus an unresolvable-identifier arm.

Measured on this tree and on two mutants:

  $ <this tree>                                    all 3 warm-up request(s) post to registered routes
                                                    (2 distinct path(s), 14 routes)               rc=0
  $ <srv.Post("/v1/chat/completions") renamed>     warm-up posts to /v1/chat/completions, which ... never
                                                    registers                                       rc=1
  $ <{ "path", kSomethingElse }>                   ... defines no string for it: an identifier it cannot
                                                    resolve is cannot-tell, not a path to skip      rc=77

The `3 request(s)` in the first line is the correction stated as a number: it was `2` before this commit, because the
chat warm-up was invisible.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

serve: the short and spec warm-ups post to /completion, a route this server never registered

1 participant