Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions src/powercontext/server/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,34 +61,26 @@
from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest
from powercontext.env_file import environment_context
from powercontext.server import database_migration
from powercontext.server.app import access_readiness_checks
from powercontext.server.background_metrics import serve_background_metrics
from powercontext.server.configuration import (
ServerConfigurationError,
resolve_server_environment_file,
server_settings_context,
)
from powercontext.server.database_migration import app as database_migration_app
from powercontext.server.factory import _ServerReadinessProbe, create_background_metrics_app, create_server_app
from powercontext.server.identity import open_server_identity_repository
from powercontext.server.inference_notice import write_inference_capability_notice
from powercontext.server.logging import configure_server_logging, shutdown_server_logging, worker_logging
from powercontext.server.metrics import ServerMetrics
from powercontext.server.observability_notice import write_observability_notice
from powercontext.server.ownership import (
apply_ownership_migration,
ownership_report,
plan_ownership_migration,
)
from powercontext.server.processing_security import build_worker_security
from powercontext.server.settings import (
MissingAuthenticationProviderError,
MissingBearerTokenError,
ServerSettings,
UnauthenticatedNonLoopbackBindError,
)
from powercontext.server.tracing import configure_server_tracing
from powercontext.server.worker_tracing import WorkerTracing

if TYPE_CHECKING:
from socket import socket
Expand Down Expand Up @@ -902,6 +894,10 @@ def run(
def _run_configured_server(settings: ServerSettings) -> None:
"""Run one already-validated configuration in the current process."""

from powercontext.server.factory import create_server_app
from powercontext.server.logging import configure_server_logging, shutdown_server_logging
from powercontext.server.tracing import configure_server_tracing

configure_server_logging(settings.logging, role=settings.runtime.artifact_processing_role)
try:
tracing = configure_server_tracing(settings.tracing, role=settings.runtime.artifact_processing_role)
Expand Down Expand Up @@ -990,6 +986,14 @@ def _run_background(settings: ServerSettings, tracing: Any) -> None:


async def _run_background_async(settings: ServerSettings, tracing: Any) -> None:
from powercontext.server.app import access_readiness_checks
from powercontext.server.background_metrics import serve_background_metrics
from powercontext.server.factory import _ServerReadinessProbe, create_background_metrics_app
from powercontext.server.logging import worker_logging
from powercontext.server.metrics import ServerMetrics
from powercontext.server.processing_security import build_worker_security
from powercontext.server.worker_tracing import WorkerTracing

config = BuiltinConfig(
code=settings.code,
runtime=settings.runtime,
Expand Down
6 changes: 3 additions & 3 deletions tests/builtin/runtime/test_artifact_processing_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,8 @@ def test_server_cli_routes_background_role_without_starting_http(monkeypatch) ->
monkeypatch.setenv("POWERCONTEXT_SERVER_DATABASE_URL", OCEANBASE_URL)
monkeypatch.setattr("powercontext.server.cli._run_background", run_background)
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)

result = CliRunner().invoke(create_cli([server_app]), ["server", "run", "--no-env-file", "--role", "background"])

Expand All @@ -222,7 +222,7 @@ def test_server_cli_routes_split_role_with_a_migrated_schedule(monkeypatch) -> N
run_background = Mock()
monkeypatch.setattr("powercontext.server.cli._run_background", run_background)
# Foreground logging must not retain CliRunner's temporary stdout after it closes.
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
result = CliRunner().invoke(create_cli([server_app]), ["server", "run", "--role", "background"])

assert result.exit_code == 0, result.output
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/test_background_startup_admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async def serve(app, configured, stopped):
assert 'powercontext_server_readiness_state{state="ready"} 1.0' in metrics.text
stopped.set()

monkeypatch.setattr(cli, "serve_background_metrics", serve)
monkeypatch.setattr("powercontext.server.background_metrics.serve_background_metrics", serve)
# SQLite supports the all role. Invoke the runner with a real local runtime
# to check its admitted lifecycle; the native OB test covers split-role CLI.
asyncio.run(cli._run_background_async(settings, ServerTracing.context_only(role="background")))
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/test_managed_startup_read_consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async def serve_metrics(application, _settings, stopped):
elif entry == "background":
# Exercise the full background runtime and readiness; replace
# only the listener lifetime so this test does not need signals.
monkeypatch.setattr(cli, "serve_background_metrics", serve_metrics)
monkeypatch.setattr("powercontext.server.background_metrics.serve_background_metrics", serve_metrics)
asyncio.run(cli._run_background_async(settings, ServerTracing.context_only(role="background")))
else:
with TestClient(
Expand Down
2 changes: 1 addition & 1 deletion tests/test_background_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ async def listener(app, configured, stopped):
events.append("listener-closed")

monkeypatch.setattr("powercontext.server.cli.open_builtin_runtime", runtime)
monkeypatch.setattr("powercontext.server.cli.serve_background_metrics", listener)
monkeypatch.setattr("powercontext.server.background_metrics.serve_background_metrics", listener)
tracing = ServerTracing.context_only(role="background")
if outcome in {"failed", "cancelled"}:
with pytest.raises(OSError if outcome == "failed" else asyncio.CancelledError):
Expand Down
77 changes: 33 additions & 44 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
import asyncio
import json
import os
import subprocess
import sys
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from types import SimpleNamespace, TracebackType
Expand Down Expand Up @@ -799,35 +797,26 @@ def test_server_identity_reset_rejects_nonpersistent_sqlite(tmp_path, url: str)
assert "identity reset requires a persistent database" in result.output


def test_service_command_provider_requires_the_complete_server_role() -> None:
script = """
import builtins

real_import = builtins.__import__

def guarded_import(name, *args, **kwargs):
if name == "fastapi" or name.startswith("fastapi."):
raise ModuleNotFoundError("blocked server dependency", name="fastapi")
return real_import(name, *args, **kwargs)

builtins.__import__ = guarded_import
try:
import powercontext.service.cli # noqa: F401
except ModuleNotFoundError as error:
if error.name != "fastapi":
raise
else:
raise AssertionError("service command loaded without the complete Server role")
"""

result = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
text=True,
check=False,
)
@pytest.mark.parametrize("dependency", ["fastapi", "fastmcp", "uvicorn"])
@pytest.mark.parametrize("installed", [None, "0.0.0"])
def test_cli_requires_the_complete_server_role(monkeypatch, dependency, installed) -> None:
def distribution_version(name):
if name == dependency:
if installed is None:
raise PackageNotFoundError(name)
return installed
return version(name)

monkeypatch.setattr("powercontext.cli.app.version", distribution_version)
cli = create_cli()
help_result = CliRunner().invoke(cli, ["--help"])

assert result.returncode == 0, result.stderr
assert help_result.exit_code == 0
assert all(command in help_result.output for command in ("capabilities", "candidate", "stats"))
for command in ("server", "service"):
result = CliRunner().invoke(cli, [command, "--help"])
assert result.exit_code == 2
assert f"No such command '{command}'" in result.output


def test_client_settings_load_environment(monkeypatch: pytest.MonkeyPatch) -> None:
Expand Down Expand Up @@ -876,8 +865,8 @@ def test_server_command_layers_partial_cli_overrides_over_environment_settings(
run_server = Mock()
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setenv("POWERCONTEXT_SERVER_ALLOW_UNAUTHENTICATED_NON_LOOPBACK", "true")
for name, value in environment.items():
monkeypatch.setenv(name, value)
Expand Down Expand Up @@ -916,8 +905,8 @@ def run_server(_application, *, host: str, port: int) -> None:

tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)

result = CliRunner().invoke(
create_cli([server_app]),
Expand Down Expand Up @@ -1007,8 +996,8 @@ def test_server_command_uses_discovered_models_for_inference_notice(
monkeypatch.delenv(name, raising=False)
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", Mock())
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)

result = CliRunner().invoke(create_cli([server_app]), ["server", "run"])

Expand Down Expand Up @@ -1183,8 +1172,8 @@ def test_server_command_rejects_an_unauthenticated_non_loopback_host_override(
run_server = Mock()
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.delenv("POWERCONTEXT_SERVER_AUTH_ENABLED", raising=False)
monkeypatch.delenv("POWERCONTEXT_SERVER_AUTH_TOKEN", raising=False)

Expand All @@ -1209,8 +1198,8 @@ def test_server_command_reports_a_friendly_error_when_auth_lacks_a_token(
run_server = Mock()
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setenv("POWERCONTEXT_SERVER_ACCESS_MODE", "enforced")
monkeypatch.delenv("POWERCONTEXT_SERVER_AUTH_TOKEN", raising=False)

Expand All @@ -1233,8 +1222,8 @@ def test_server_command_lets_a_loopback_override_repair_an_unsafe_environment_ho
run_server = Mock()
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setenv("POWERCONTEXT_SERVER_HTTP_HOST", "0.0.0.0") # noqa: S104 - unsafe env value the CLI repairs.

result = CliRunner().invoke(
Expand All @@ -1253,8 +1242,8 @@ def test_server_command_does_not_load_client_settings(monkeypatch: pytest.Monkey
monkeypatch.setenv("POWERCONTEXT_CLIENT_SERVER_URL", "not-a-url")
monkeypatch.setenv("POWERCONTEXT_SERVER_ACCESS_MODE", "disabled")
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)

result = CliRunner().invoke(create_cli([server_app]), ["server", "run", "--no-env-file"])

Expand Down
4 changes: 2 additions & 2 deletions tests/test_docker_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def test_documented_container_invocation_starts_out_of_the_box(monkeypatch: pyte
run_server = Mock()
tracing = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: tracing)
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: tracing)
# Reproduce the container's environment exactly, with no ambient POWERCONTEXT_SERVER_* leaking in.
for name in list(os.environ):
if name.startswith("POWERCONTEXT_SERVER_"):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_docs_remote_access_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ def test_docs_expose_a_non_loopback_bind_command() -> None:
def test_documented_server_run_command_starts(command: _DocumentedServerRun, monkeypatch: pytest.MonkeyPatch) -> None:
run_server = Mock()
monkeypatch.setattr("powercontext.server.cli._run_server", run_server)
monkeypatch.setattr("powercontext.server.cli.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.cli.configure_server_tracing", lambda _config, **_kwargs: Mock())
monkeypatch.setattr("powercontext.server.logging.configure_server_logging", lambda _config, **_kwargs: None)
monkeypatch.setattr("powercontext.server.tracing.configure_server_tracing", lambda _config, **_kwargs: Mock())
# Reproduce only the env the doc block sets, with no ambient POWERCONTEXT_SERVER_* leaking in.
for name in list(os.environ):
if name.startswith("POWERCONTEXT_SERVER_"):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_metrics_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ async def serve(app, settings, stopped):
stopped.set()

monkeypatch.setattr("powercontext.server.cli.open_builtin_runtime", open_runtime)
monkeypatch.setattr("powercontext.server.cli.serve_background_metrics", serve)
monkeypatch.setattr("powercontext.server.background_metrics.serve_background_metrics", serve)
await _run_background_async(
ServerSettings(database=SQLiteConfig()), ServerTracing.context_only(role="background")
)
Expand Down
Loading