From c66985dca00a71bca82581bbd4faf4fe35eb5ffa Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:24:23 -0600 Subject: [PATCH 1/8] fix(py): write runtime files under the CLI's project root RuntimeManager wrote .genkit/runtimes to cwd while the CLI reads it from findProjectRoot(). From a subdirectory the Dev UI showed 0 actions. Walk ancestors with the CLI's marker list; fall back to cwd. --- packages/genkit/src/genkit/_ai/_runtime.py | 34 +++++++++++++++- .../genkit/tests/genkit/veneer/server_test.py | 39 +++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_runtime.py b/packages/genkit/src/genkit/_ai/_runtime.py index 0e3f0d1f9..8ec55e5f0 100644 --- a/packages/genkit/src/genkit/_ai/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_runtime.py @@ -36,6 +36,35 @@ logger = get_logger(__name__) DEFAULT_RUNTIME_DIR_NAME = '.genkit/runtimes' + +# Same list as the CLI's ``findProjectRoot`` (genkit-tools/common/src/utils/utils.ts). +# The CLI reads ``.genkit/runtimes`` under that root, so the runtime file has to +# land there too. +PROJECT_ROOT_MARKERS: tuple[str, ...] = ( + 'package.json', + 'go.mod', + 'pyproject.toml', + 'requirements.txt', + 'pom.xml', + 'build.gradle', + 'build.gradle.kts', + 'pubspec.yaml', +) + + +def find_project_root(start: Path | None = None) -> Path: + """Nearest ancestor of ``start`` (default cwd) holding a project marker. + + Mirrors the CLI: walk up from cwd, stop before the filesystem root, and + fall back to cwd when no marker is found. + """ + cwd = Path(start) if start is not None else Path.cwd() + current = cwd + while current != Path(current.anchor): + if any((current / marker).exists() for marker in PROJECT_ROOT_MARKERS): + return current + current = current.parent + return cwd ACTIVE_CLEANUPS: list[Callable[[], None]] = [] # RLock so a SIGINT/SIGTERM mid-update can re-enter: signal handlers run on the # main thread, and a plain Lock would deadlock if that thread already holds it. @@ -204,7 +233,8 @@ def __init__( Args: spec: The server specification for the reflection server. runtime_dir: The directory to store the runtime file in. - Defaults to .genkit/runtimes in the current directory. + Defaults to .genkit/runtimes under the project root, + found the same way the CLI finds it. lazy_write: If True, the runtime file will not be written immediately on context entry. It must be written manually by calling write_runtime_file(). @@ -213,7 +243,7 @@ def __init__( self.spec: ServerSpec = spec self._secret: str | None = secret if runtime_dir is None: - self._runtime_dir: Path = Path(Path.cwd()) / DEFAULT_RUNTIME_DIR_NAME + self._runtime_dir: Path = find_project_root() / DEFAULT_RUNTIME_DIR_NAME else: self._runtime_dir = Path(runtime_dir) diff --git a/packages/genkit/tests/genkit/veneer/server_test.py b/packages/genkit/tests/genkit/veneer/server_test.py index 022d96f47..effece7fd 100644 --- a/packages/genkit/tests/genkit/veneer/server_test.py +++ b/packages/genkit/tests/genkit/veneer/server_test.py @@ -9,6 +9,8 @@ import pathlib import tempfile +import pytest + from genkit._ai._runtime import RuntimeManager from genkit._core._reflection import ServerSpec @@ -63,3 +65,40 @@ def test_runtime_manager() -> None: runtime_path = rm.write_runtime_file() assert pathlib.Path(new_dir).exists() assert runtime_path.exists() + + +def test_find_project_root_matches_cli_markers(tmp_path: pathlib.Path) -> None: + """Runtime files land where the CLI's ``findProjectRoot`` looks.""" + from genkit._ai._runtime import find_project_root + + project = tmp_path / 'repo' + sub = project / 'services' / 'api' + sub.mkdir(parents=True) + (project / 'pyproject.toml').write_text('') + + assert find_project_root(sub) == project + (sub.parent / 'go.mod').write_text('') + assert find_project_root(sub) == sub.parent + + +def test_find_project_root_falls_back_to_start(tmp_path: pathlib.Path) -> None: + from genkit._ai._runtime import find_project_root + + bare = tmp_path / 'no' / 'markers' + bare.mkdir(parents=True) + root = find_project_root(bare) + # A marker above tmp_path (e.g. a pyproject in a parent) is a legitimate hit. + assert root == bare or bare.is_relative_to(root) + + +def test_runtime_manager_defaults_to_project_root(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: + project = tmp_path / 'repo' + sub = project / 'src' / 'app' + sub.mkdir(parents=True) + (project / 'requirements.txt').write_text('') + monkeypatch.chdir(sub) + + with RuntimeManager(spec=ServerSpec(port=3100)) as rm: + path = rm.write_runtime_file() + assert path.parent == project / '.genkit' / 'runtimes' + assert not path.exists() From 5165dcbbc1bb6dc2919fbae2da8d89304eece174 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:27:53 -0600 Subject: [PATCH 2/8] fix(py): reflection v1 flush, Python tracebacks, protocol hygiene - /api/runAction awaits flush_instrumentations() before answering, as v2 and JS do, so the root span is exported when the response lands. - Error details.stack carries the Python traceback when empty, so genkit flow:run prints Python frames (matches v2). - /api/notify also enables log export and warns on spec-version mismatch; /api/__health?id= answers 503 for another runtime; a missing runAction key is 400, not a KeyError 500. --- .../genkit/src/genkit/_core/_reflection.py | 53 ++++++++++++- .../genkit/core/endpoints/reflection_test.py | 75 +++++++++++++++++++ 2 files changed, 126 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index 1d848b111..f0887638e 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -23,6 +23,7 @@ import os import signal import threading +import traceback from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable from contextlib import asynccontextmanager from dataclasses import dataclass, field @@ -49,6 +50,8 @@ from genkit._core._reflection_config import REFLECTION_SECRET_HEADER, secrets_equal from genkit._core._registry import Registry from genkit._core._telemetry._http import connect_developer_ui_collector +from genkit._core._telemetry._instrumentation import flush_instrumentations +from genkit._core._telemetry._log_exporter import enable_log_export logger = get_logger(__name__) @@ -171,6 +174,9 @@ async def execute(self) -> None: payload: dict[str, Any] = {'result': result} if output.trace_id: payload['telemetry'] = {'traceId': output.trace_id, 'spanId': output.span_id} + # Export the root span before answering, as v2 and JS do, so the + # Dev UI trace view is complete when the response lands. + await asyncio.to_thread(flush_instrumentations) self.queue.put_nowait(json.dumps(payload)) except asyncio.CancelledError: raise @@ -182,6 +188,11 @@ async def execute(self) -> None: # terminal noise. logger.debug('Action failed: %s: %s', type(e).__name__, e, exc_info=True) error = get_reflection_json(interrupt_escape_error(e) or e, trace_id=self.trace_id) + if error.details is not None and not error.details.stack and e.__traceback__: + # Same as v2: `genkit flow:run` prints this, so give it Python frames. + stack = ''.join(traceback.format_exception(type(e), e, e.__traceback__)) + error = error.model_copy(update={'details': error.details.model_copy(update={'stack': stack})}) + await asyncio.to_thread(flush_instrumentations) self.queue.put_nowait(json.dumps({'error': error.model_dump(by_alias=True)})) finally: self.trace_ready.set() @@ -235,6 +246,25 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self._app(scope, receive, send) +_REFLECTION_API_SPEC_VERSION = 1 + + +def _warn_on_spec_version_mismatch(spec_version: object) -> None: + """Same warnings as JS ``/api/notify`` when CLI and runtime disagree.""" + if spec_version == _REFLECTION_API_SPEC_VERSION: + return + if not isinstance(spec_version, int | float) or spec_version < _REFLECTION_API_SPEC_VERSION: + logger.warning( + 'WARNING: Genkit CLI version may be outdated. Please update `genkit-cli` to the latest version.' + ) + else: + logger.warning( + 'Genkit CLI is newer than runtime library. Some feature may not be supported. ' + 'Consider upgrading your runtime library version (debug info: expected ' + f'{_REFLECTION_API_SPEC_VERSION}, got {spec_version}).' + ) + + def create_reflection_asgi_app( registry: Registry, on_startup: LifecycleHook | None = None, @@ -244,7 +274,16 @@ def create_reflection_asgi_app( ) -> Starlette: active_actions: dict[str, asyncio.Task[Any]] = {} - async def health(_: Request) -> JSONResponse: + async def health(req: Request) -> Response: + requested_id = req.query_params.get('id') + if requested_id: + server = req.scope.get('server') + port = server[1] if server else None + runtime_id = f'{os.getpid()}-{port}' if port else str(os.getpid()) + if requested_id != runtime_id: + # Matches JS: a stale runtime file pointing at a reused port + # must not look healthy to the CLI. + return Response('Invalid runtime ID', status_code=503) await registry.initialize_all_plugins() return JSONResponse({'status': 'OK'}) @@ -314,12 +353,16 @@ async def notify(req: Request) -> JSONResponse: body = await req.json() except Exception: body = None + spec_version: object = None if isinstance(body, dict): raw = body.get('telemetryServerUrl') if isinstance(raw, str) and raw: url = raw + spec_version = body.get('reflectionApiSpecVersion') if url: connect_developer_ui_collector(url=url) + enable_log_export(url=url) + _warn_on_spec_version_mismatch(spec_version) return JSONResponse({}, headers={'x-genkit-version': version}) async def cancel(req: Request) -> JSONResponse: @@ -333,7 +376,13 @@ async def cancel(req: Request) -> JSONResponse: async def run(req: Request) -> Response: payload = await req.json() - key = payload['key'] + key = payload.get('key') if isinstance(payload, dict) else None + if not isinstance(key, str) or not key: + return JSONResponse( + {'error': 'key is required'}, + status_code=400, + headers={'x-genkit-version': version}, + ) action = await resolve_runnable_key(registry, key) if not action: return JSONResponse({'error': f'Action not found: {key}'}, status_code=404) diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py index 6101dd2cb..cd7db0bfc 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py @@ -619,3 +619,78 @@ async def order(order_id: str) -> str: assert error['message'] == 'no order 99' assert error['code'] == 5 assert error['details']['traceId'] == response.headers['x-genkit-trace-id'] + + +@pytest.mark.asyncio +async def test_run_action_flushes_spans_before_responding(monkeypatch: pytest.MonkeyPatch) -> None: + """v1 matches v2: the root span is exported by the time the response lands.""" + from genkit._core import _reflection + + events: list[str] = [] + monkeypatch.setattr(_reflection, 'flush_instrumentations', lambda: events.append('flush')) + ai = Genkit() + + @ai.flow() + async def order_dish(dish: str) -> str: + events.append('run') + return dish + + app = create_reflection_asgi_app(ai._registry) + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + response = await client.post('/api/runAction', json={'key': '/flow/order_dish', 'input': 'Tartine'}) + + assert response.status_code == 200 + assert events == ['run', 'flush'] + + +@pytest.mark.asyncio +async def test_run_action_error_carries_python_traceback() -> None: + ai = Genkit() + + @ai.flow() + async def check_allergens(dish: str) -> str: + raise ValueError(f'unknown allergen profile for {dish}') + + app = create_reflection_asgi_app(ai._registry) + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + response = await client.post('/api/runAction', json={'key': '/flow/check_allergens', 'input': 'Tartine'}) + + stack = response.json()['error']['details']['stack'] + assert 'Traceback (most recent call last)' in stack + assert 'check_allergens' in stack + assert 'ValueError: unknown allergen profile for Tartine' in stack + + +@pytest.mark.asyncio +async def test_run_action_missing_key_is_400(asgi_client: AsyncClient) -> None: + response = await asgi_client.post('/api/runAction', json={'input': 'Tartine'}) + assert response.status_code == 400 + assert response.json() == {'error': 'key is required'} + + +@pytest.mark.asyncio +async def test_health_rejects_foreign_runtime_id(asgi_client: AsyncClient) -> None: + """Matches JS: `?id=` for another runtime answers 503.""" + assert (await asgi_client.get('/api/__health', params={'id': 'not-me'})).status_code == 503 + assert (await asgi_client.get('/api/__health')).status_code == 200 + + +@pytest.mark.asyncio +async def test_notify_enables_log_export_and_warns_on_old_cli( + asgi_client: AsyncClient, monkeypatch: pytest.MonkeyPatch +) -> None: + from genkit._core import _reflection + + calls: list[tuple[str, str]] = [] + warnings: list[str] = [] + monkeypatch.setattr(_reflection, 'connect_developer_ui_collector', lambda url: calls.append(('connect', url))) + monkeypatch.setattr(_reflection, 'enable_log_export', lambda url: calls.append(('logs', url))) + monkeypatch.setattr(_reflection.logger, 'warning', lambda msg, *a, **k: warnings.append(msg)) + + response = await asgi_client.post( + '/api/notify', json={'telemetryServerUrl': 'http://localhost:4033', 'reflectionApiSpecVersion': 0} + ) + + assert response.status_code == 200 + assert calls == [('connect', 'http://localhost:4033'), ('logs', 'http://localhost:4033')] + assert any('outdated' in w for w in warnings) From 8b1cb897bb9abadd970d3cd446e3bda6cbc98753 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:27:53 -0600 Subject: [PATCH 3/8] fix(py): lift reflection v2 WebSocket cap to 100 MiB, send integer pid websockets defaults max_size to 1 MiB; a runAction with one screenshot closed the socket with 1009. Match the CLI's 100 MiB. register now sends pid and reflectionApiSpecVersion as integers. --- .../genkit/src/genkit/_core/_reflection_v2.py | 7 ++++ .../tests/genkit/core/reflection_v2_test.py | 38 ++++++++++++++++++- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_reflection_v2.py b/packages/genkit/src/genkit/_core/_reflection_v2.py index 0ec2a611e..4fe14279a 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -78,6 +78,7 @@ logger = get_logger(__name__) GENKIT_REFLECTION_API_SPEC_VERSION = 1 +_MAX_MESSAGE_BYTES = 100 * 1024 * 1024 JSON_RPC_METHOD_NOT_FOUND = -32601 JSON_RPC_INVALID_PARAMS = -32602 @@ -178,6 +179,9 @@ async def run_forever(self) -> None: self.ws_url, ping_interval=20, ping_timeout=20, + # websockets defaults to 1 MiB; one screenshot in runAction or + # GoogleAI's listActions exceeds that. Match the CLI's 100 MiB. + max_size=_MAX_MESSAGE_BYTES, ) as ws: self.ws = ws attempt = 0 @@ -287,6 +291,9 @@ async def register(self) -> None: envs=['dev'], secret=self.secret, ).model_dump(by_alias=True, exclude_none=True) + # The generated schema types these as float; send integers like JS. + params['pid'] = os.getpid() + params['reflectionApiSpecVersion'] = GENKIT_REFLECTION_API_SPEC_VERSION try: result = await self.send_request('register', params) if isinstance(result, dict) and (telemetry_url := result.get('telemetryServerUrl')): diff --git a/packages/genkit/tests/genkit/core/reflection_v2_test.py b/packages/genkit/tests/genkit/core/reflection_v2_test.py index bad5af828..6dda3c8bb 100644 --- a/packages/genkit/tests/genkit/core/reflection_v2_test.py +++ b/packages/genkit/tests/genkit/core/reflection_v2_test.py @@ -170,9 +170,11 @@ async def test_reflection_server_v2_register(fake_manager: FakeReflectionManager assert isinstance(params, dict) assert params.get('name') == 'test-app' assert params.get('id') - assert isinstance(params.get('pid'), (int, float)) + # Integers on the wire, like JS (the generated schema types them as float). + assert type(params.get('pid')) is int assert str(params.get('genkitVersion', '')).startswith('py/') - assert isinstance(params.get('reflectionApiSpecVersion'), (int, float)) + assert params.get('reflectionApiSpecVersion') == 1 + assert type(params.get('reflectionApiSpecVersion')) is int envs = params.get('envs') assert isinstance(envs, list) and envs == ['dev'] finally: @@ -1142,3 +1144,35 @@ async def concierge_agent(_init: Any, input_stream: Any, send_chunk: Any) -> dic assert resp['result']['result'] == {'context': caller} finally: await _stop_client(client, task) + + +@pytest.mark.asyncio +async def test_reflection_v2_accepts_messages_over_one_mib(fake_manager: FakeReflectionManager) -> None: + """A runAction carrying a screenshot (>1 MiB) must not close the socket with 1009.""" + registry = Registry() + + async def measure(data: str) -> int: + return len(data) + + registry.register_action_from_instance(Action(ActionKind.CUSTOM, 'test/measure', measure)) + payload = 'x' * (3 * 1024 * 1024 // 2) + + client, task = await _run_client_lifecycle(registry, fake_manager) + try: + await ack_register(fake_manager) + await fake_manager.write_rpc({ + 'jsonrpc': '2.0', + 'method': 'runAction', + 'params': {'key': '/custom/test/measure', 'input': payload}, + 'id': 'big', + }) + resp: dict[str, Any] | None = None + while resp is None: + msg = await fake_manager.read_rpc(timeout=5.0) + if msg.get('method') == 'runActionState': + continue + resp = msg + assert resp.get('id') == 'big' + assert resp['result']['result'] == len(payload) + finally: + await _stop_client(client, task) From 60081a7d69a8235f8e775a41c91d527b33d0eb10 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:28:56 -0600 Subject: [PATCH 4/8] fix(py): log to stderr and make value/schema registration idempotent structlog's default factory printed to stdout, breaking `python cli.py | jq .`. Default to stderr unless the app set a factory. define_value / define_schema now overwrite on re-registration, like flows, tools, and prompts, so re-running a Jupyter cell works. --- packages/genkit/src/genkit/_ai/_aio.py | 6 +++-- packages/genkit/src/genkit/_core/_logger.py | 12 ++++++++- packages/genkit/src/genkit/_core/_registry.py | 15 +++++------ .../genkit/tests/genkit/core/logger_test.py | 23 +++++++++++++++++ .../genkit/tests/genkit/veneer/lookup_test.py | 25 +++++++++++++++---- 5 files changed, 66 insertions(+), 15 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index cd8d47ec7..5273425ac 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -715,10 +715,12 @@ def lookup_value(self, *, kind: str, name: str) -> object | None: def define_value(self, *, kind: str, name: str, value: object) -> None: """Store ``value`` under ``kind`` and ``name`` for later ``lookup_value``. + Defining the same kind and name again replaces the value, so a + re-run notebook cell does not fail. + Raises: ValueError: ``kind`` is one Genkit owns (use ``define_middleware``, - ``define_format``, or ``Genkit(model=...)``), ``value`` is None, - or a value is already defined under this kind and name. + ``define_format``, or ``Genkit(model=...)``), or ``value`` is None. """ if kind in _CORE_VALUE_KINDS: raise ValueError(f'define_value kind {kind!r} is reserved; use {_CORE_VALUE_KINDS[kind]} instead.') diff --git a/packages/genkit/src/genkit/_core/_logger.py b/packages/genkit/src/genkit/_core/_logger.py index 0ae2a4e17..f338b1b73 100644 --- a/packages/genkit/src/genkit/_core/_logger.py +++ b/packages/genkit/src/genkit/_core/_logger.py @@ -7,6 +7,7 @@ import logging import os +import sys import threading from collections.abc import Awaitable, Callable from typing import Protocol, cast @@ -102,7 +103,16 @@ def configure_structlog_level() -> bool: """ if _app_chose_level(): return False - structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(resolve_level())) + if structlog.is_configured(): + structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(resolve_level())) + else: + # structlog's default factory prints to stdout, which corrupts + # `python cli.py | jq .`. Logs go to stderr; an app that already + # picked a logger factory keeps it. + structlog.configure( + wrapper_class=structlog.make_filtering_bound_logger(resolve_level()), + logger_factory=structlog.PrintLoggerFactory(file=sys.stderr), + ) ignored = unrecognized_level() if ignored is not None: get_logger(__name__).warning( diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 908899655..8034fdb2f 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -467,16 +467,15 @@ def register_value(self, kind: str, name: str, value: object) -> None: value: The value to be registered. Can be of any non-serializable type. - Raises: - ValueError: If a value with the given kind and name is already - registered. + Registering the same kind and name again replaces the value. """ with self._lock: if kind not in self._value_by_kind_and_name: self._value_by_kind_and_name[kind] = {} if name in self._value_by_kind_and_name[kind]: - raise ValueError(f'value for kind "{kind}" and name "{name}" is already registered') + # Re-running a notebook cell re-registers; overwrite like flows/tools do. + logger.debug(f'Overwriting value for kind "{kind}" and name "{name}"') self._value_by_kind_and_name[kind][name] = value @@ -818,15 +817,17 @@ def register_schema(self, name: str, schema: dict[str, object], schema_type: typ schema: The schema data (JSON schema format). schema_type: Optional Pydantic model class for runtime validation. - Raises: - ValueError: If a schema with the given name is already registered. + Registering the same name again replaces the schema. """ with self._lock: if name in self._schemas_by_name: - raise ValueError(f'Schema "{name}" is already registered') + # Re-running a notebook cell re-registers; overwrite like flows/tools do. + logger.debug(f'Overwriting schema "{name}"') self._schemas_by_name[name] = schema if schema_type is not None: self._schema_types_by_name[name] = schema_type + else: + self._schema_types_by_name.pop(name, None) logger.debug(f'Registered schema "{name}"') def lookup_schema(self, name: str) -> dict[str, object] | None: diff --git a/packages/genkit/tests/genkit/core/logger_test.py b/packages/genkit/tests/genkit/core/logger_test.py index ee538ee9a..ef066f606 100644 --- a/packages/genkit/tests/genkit/core/logger_test.py +++ b/packages/genkit/tests/genkit/core/logger_test.py @@ -469,3 +469,26 @@ def test_is_debug_enabled_when_the_level_check_cannot_run() -> None: structlog.configure(wrapper_class=structlog.stdlib.BoundLogger) assert is_debug_enabled(get_logger('test')) is True + + +@pytest.mark.usefixtures('_restore_structlog') +def test_configure_structlog_level_logs_to_stderr(capsys: pytest.CaptureFixture[str]) -> None: + """`python cli.py | jq .` must see only program output on stdout.""" + structlog.reset_defaults() + with mock.patch.dict(os.environ, clear=True): + assert configure_structlog_level() is True + get_logger('test').warning('quota low') + + captured = capsys.readouterr() + assert 'quota low' not in captured.out + assert 'quota low' in captured.err + + +@pytest.mark.usefixtures('_restore_structlog') +def test_configure_structlog_level_keeps_app_logger_factory() -> None: + factory = structlog.PrintLoggerFactory() + structlog.reset_defaults() + structlog.configure(logger_factory=factory) + with mock.patch.dict(os.environ, clear=True): + assert configure_structlog_level() is True + assert structlog.get_config()['logger_factory'] is factory diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index c702c8590..6cd6b8423 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -183,15 +183,30 @@ def test_lookup_value_unknown_returns_none() -> None: assert ai.lookup_value(kind='other-kind', name='banner') is None -def test_define_value_same_name_twice_raises() -> None: - """Defining the same kind and name twice raises ValueError and the first value stays.""" +def test_define_value_same_name_twice_overwrites() -> None: + """Re-running a notebook cell redefines the value instead of raising.""" ai = Genkit() ai.define_value(kind='catalog', name='banner', value='first') + ai.define_value(kind='catalog', name='banner', value='second') - with pytest.raises(ValueError, match='already registered'): - ai.define_value(kind='catalog', name='banner', value='second') + assert ai.lookup_value(kind='catalog', name='banner') == 'second' - assert ai.lookup_value(kind='catalog', name='banner') == 'first' + +def test_define_schema_same_name_twice_overwrites() -> None: + from pydantic import BaseModel + + class Dish(BaseModel): + name: str + + class DishV2(BaseModel): + name: str + allergens: list[str] + + ai = Genkit() + ai.define_schema('Dish', Dish) + ai.define_schema('Dish', DishV2) + + assert ai._registry.lookup_schema_type('Dish') is DishV2 def test_define_value_requires_keywords() -> None: From 81e0832eb36fd5dbe027d347ba05db2007c9d52f Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:30:28 -0600 Subject: [PATCH 5/8] fix(py): run_main in a running loop, port-exhaustion message, empty runtime dirs - ai.run_main() under Jupyter/IPython raises a RuntimeError that points to `await main()` and closes the coroutine (no unawaited warning). - The reflection port-range error was unreachable; instance #101 got a bare EADDRINUSE. Name the cause and the fix. - RuntimeManager removes .genkit/runtimes and .genkit when it leaves them empty. --- packages/genkit/src/genkit/_ai/_aio.py | 23 ++++++++++++- packages/genkit/src/genkit/_ai/_runtime.py | 19 +++++++++++ .../genkit/veneer/reflection_server_test.py | 33 +++++++++++++++++++ .../genkit/tests/genkit/veneer/server_test.py | 22 +++++++++++++ 4 files changed, 96 insertions(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 5273425ac..20e019d5e 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -1110,7 +1110,15 @@ def _bind_reflection_socket(host: str, port: int, *, pinned: bool) -> socket.soc continue sock.listen(2048) return sock - raise last or OSError(f'no available port in range {port}-{port + 99}') + if pinned: + raise last or OSError(f'port {port} is not available') + # Each Genkit() with reflection on holds one port; a notebook that + # re-runs `ai = Genkit(...)` exhausts the range. + raise OSError( + f'No free reflection port in {port}-{port + 99}. Each Genkit() instance with the Dev UI ' + 'reflection server on (GENKIT_ENV=dev) holds one port; reuse one instance instead of ' + 'creating a new one per cell or request.' + ) from last def _start_reflection_background(self) -> None: """Start the Dev UI reflection server in a background daemon thread. @@ -1290,6 +1298,19 @@ async def main() -> None: # stays up for the Dev UI until you press Ctrl+C. ``` """ + try: + asyncio.get_running_loop() + except RuntimeError: + pass + else: + # Jupyter, IPython, and async frameworks already run a loop, and + # asyncio.run would fail with a raw RuntimeError plus an + # unawaited-coroutine warning. + coro.close() + raise RuntimeError( + 'ai.run_main() cannot be called from a running event loop (Jupyter, IPython, or an async ' + 'framework). Use `await main()` instead.' + ) if not self._reflection_config.enabled: return run_loop(coro) diff --git a/packages/genkit/src/genkit/_ai/_runtime.py b/packages/genkit/src/genkit/_ai/_runtime.py index 8ec55e5f0..f0959b111 100644 --- a/packages/genkit/src/genkit/_ai/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_runtime.py @@ -123,12 +123,28 @@ def _remove_file(file_path: Path | None) -> bool: try: if file_path.exists(): file_path.unlink() + _remove_empty_runtime_dirs(file_path.parent) return True except Exception as e: print(f'Error deleting {file_path}: {e}') # noqa: T201 - atexit handler, logger unavailable return False +def _remove_empty_runtime_dirs(runtime_dir: Path) -> None: + """Drop ``.genkit/runtimes`` and ``.genkit`` if this process left them empty. + + ``rmdir`` only removes an empty directory, so another runtime's file or + the CLI's traces keep them in place. + """ + for directory in (runtime_dir, runtime_dir.parent): + if directory.name not in ('runtimes', '.genkit'): + return + try: + directory.rmdir() + except OSError: + return + + def _register_atexit_cleanup_handler(path_to_remove: Path | None) -> None: """Defines and registers the synchronous atexit cleanup handler for a path. @@ -342,3 +358,6 @@ def cleanup(self) -> None: logger.debug(f'Cleaning up runtime file: {self._runtime_file_path}') _ = _remove_file(self._runtime_file_path) self._runtime_file_path = None + else: + # lazy_write: the directory exists but no file was ever written. + _remove_empty_runtime_dirs(self._runtime_dir) diff --git a/packages/genkit/tests/genkit/veneer/reflection_server_test.py b/packages/genkit/tests/genkit/veneer/reflection_server_test.py index 6a2407a21..15d890c2a 100644 --- a/packages/genkit/tests/genkit/veneer/reflection_server_test.py +++ b/packages/genkit/tests/genkit/veneer/reflection_server_test.py @@ -396,3 +396,36 @@ def test_reflection_server_configures_logging_when_app_has_none() -> None: lg.handlers = handlers lg.filters = filters lg.propagate = propagate + + +def test_exhausted_port_range_names_the_cause(monkeypatch: pytest.MonkeyPatch) -> None: + """Instance #101 gets an actionable message, not a bare EADDRINUSE.""" + real_bind = socket.socket.bind + + def busy(self: socket.socket, addr: Any) -> None: # noqa: ANN401 + raise OSError(48, 'Address already in use') + + monkeypatch.setattr(socket.socket, 'bind', busy) + try: + with pytest.raises(OSError, match='reuse one instance') as exc: + Genkit._bind_reflection_socket('127.0.0.1', 3100, pinned=False) # pyright: ignore[reportPrivateUsage] + finally: + monkeypatch.setattr(socket.socket, 'bind', real_bind) + assert isinstance(exc.value.__cause__, OSError) + + +@pytest.mark.asyncio +async def test_run_main_inside_running_loop_points_to_await() -> None: + """Jupyter already runs a loop: say `await main()` and don't leak an unawaited coroutine.""" + import warnings + + with mock.patch.dict(os.environ, {}, clear=True): + ai = Genkit() + + async def main() -> str: + return 'Smoked Salmon Tartine' + + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + with pytest.raises(RuntimeError, match=r'await main\(\)'): + ai.run_main(main()) diff --git a/packages/genkit/tests/genkit/veneer/server_test.py b/packages/genkit/tests/genkit/veneer/server_test.py index effece7fd..26e4b40a5 100644 --- a/packages/genkit/tests/genkit/veneer/server_test.py +++ b/packages/genkit/tests/genkit/veneer/server_test.py @@ -102,3 +102,25 @@ def test_runtime_manager_defaults_to_project_root(tmp_path: pathlib.Path, monkey path = rm.write_runtime_file() assert path.parent == project / '.genkit' / 'runtimes' assert not path.exists() + + +def test_runtime_manager_removes_empty_runtime_dirs(tmp_path: pathlib.Path) -> None: + """Exiting leaves no empty `.genkit/runtimes` behind in the project.""" + runtime_dir = tmp_path / '.genkit' / 'runtimes' + with RuntimeManager(spec=ServerSpec(port=3100), runtime_dir=runtime_dir): + assert runtime_dir.exists() + assert not (tmp_path / '.genkit').exists() + + with RuntimeManager(spec=ServerSpec(port=3100), runtime_dir=runtime_dir, lazy_write=True): + assert runtime_dir.exists() + assert not (tmp_path / '.genkit').exists() + + +def test_runtime_manager_keeps_dirs_with_other_files(tmp_path: pathlib.Path) -> None: + runtime_dir = tmp_path / '.genkit' / 'runtimes' + runtime_dir.mkdir(parents=True) + (tmp_path / '.genkit' / 'traces.json').write_text('{}') + with RuntimeManager(spec=ServerSpec(port=3100), runtime_dir=runtime_dir): + pass + assert not runtime_dir.exists() + assert (tmp_path / '.genkit' / 'traces.json').exists() From 70ed5b487ceaaf370c55771bb2006722ce1cecf8 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 00:46:45 -0600 Subject: [PATCH 6/8] fix(py): only remove runtime dirs this process created genkit start creates and watches .genkit/runtimes before it spawns the app. Removing that directory on exit and recreating it on the next start leaves the CLI's chokidar 4 watcher blind to the new runtime file, so a restarted app never shows up in the Dev UI. Track which directory levels RuntimeManager created and remove only those. --- packages/genkit/src/genkit/_ai/_runtime.py | 48 ++++++++++++------- .../genkit/tests/genkit/veneer/server_test.py | 12 ++++- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_runtime.py b/packages/genkit/src/genkit/_ai/_runtime.py index f0959b111..21c87a52b 100644 --- a/packages/genkit/src/genkit/_ai/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_runtime.py @@ -24,7 +24,7 @@ import signal import sys import threading -from collections.abc import Callable +from collections.abc import Callable, Sequence from datetime import datetime from pathlib import Path from types import FrameType, TracebackType @@ -111,9 +111,14 @@ def handle_signal(signum: int, frame: FrameType | None) -> None: pass -def _remove_file(file_path: Path | None) -> bool: +def _remove_file(file_path: Path | None, created_dirs: Sequence[Path] = ()) -> bool: """Synchronously attempts to delete the file. + Args: + file_path: The runtime file to delete. + created_dirs: Directories this process created for the file, innermost + first; each is removed if it is left empty. + Returns: True if cleanup was successful or file didn't exist, False on error. """ @@ -123,33 +128,35 @@ def _remove_file(file_path: Path | None) -> bool: try: if file_path.exists(): file_path.unlink() - _remove_empty_runtime_dirs(file_path.parent) + _remove_empty_dirs(created_dirs) return True except Exception as e: print(f'Error deleting {file_path}: {e}') # noqa: T201 - atexit handler, logger unavailable return False -def _remove_empty_runtime_dirs(runtime_dir: Path) -> None: - """Drop ``.genkit/runtimes`` and ``.genkit`` if this process left them empty. +def _remove_empty_dirs(created_dirs: Sequence[Path]) -> None: + """Drop the runtime directories this process created, if left empty. - ``rmdir`` only removes an empty directory, so another runtime's file or - the CLI's traces keep them in place. + Only directories that did not exist on entry are removed. ``genkit start`` + creates and watches ``.genkit/runtimes`` before it spawns the app; removing + and recreating that directory leaves the CLI's watcher blind to the next + runtime file. ``rmdir`` only removes an empty directory, so another + runtime's file or the CLI's traces keep them in place. """ - for directory in (runtime_dir, runtime_dir.parent): - if directory.name not in ('runtimes', '.genkit'): - return + for directory in created_dirs: try: directory.rmdir() except OSError: return -def _register_atexit_cleanup_handler(path_to_remove: Path | None) -> None: +def _register_atexit_cleanup_handler(path_to_remove: Path | None, created_dirs: Sequence[Path] = ()) -> None: """Defines and registers the synchronous atexit cleanup handler for a path. Args: path_to_remove: The path to the file that needs cleanup. + created_dirs: Directories this process created, removed if left empty. """ if not path_to_remove: logger.warning('Cannot register atexit cleanup: runtime file path not set.') @@ -157,7 +164,7 @@ def _register_atexit_cleanup_handler(path_to_remove: Path | None) -> None: def sync_cleanup() -> None: # TODO(#4335): Neither print nor logger appears to work during atexit. - _ = _remove_file(path_to_remove) + _ = _remove_file(path_to_remove, created_dirs) logger.debug(f'Registering synchronous atexit cleanup for {path_to_remove}') _ = atexit.register(sync_cleanup) @@ -265,12 +272,19 @@ def __init__( self.lazy_write: bool = lazy_write self._runtime_file_path: Path | None = None + # Runtime directories this manager created, innermost first. + self._created_dirs: list[Path] = [] + + def _ensure_runtime_dir(self) -> None: + """Create the runtime directory, remembering which levels were new.""" + self._created_dirs = [d for d in (self._runtime_dir, self._runtime_dir.parent) if not d.exists()] + _ = self._runtime_dir.mkdir(parents=True, exist_ok=True) async def __aenter__(self) -> RuntimeManager: """Create the runtime directory and file.""" try: logger.debug(f'Ensuring runtime directory exists: {self._runtime_dir}') - _ = self._runtime_dir.mkdir(parents=True, exist_ok=True) + self._ensure_runtime_dir() if not self.lazy_write: _ = self.write_runtime_file() @@ -303,7 +317,7 @@ def __enter__(self) -> RuntimeManager: """Synchronous entry point: Create the runtime directory and file.""" try: logger.debug(f'[sync] Ensuring runtime directory exists: {self._runtime_dir}') - _ = self._runtime_dir.mkdir(parents=True, exist_ok=True) + self._ensure_runtime_dir() if not self.lazy_write: _ = self.write_runtime_file() @@ -343,7 +357,7 @@ def write_runtime_file(self) -> Path: return self._runtime_file_path self._runtime_file_path = _create_and_write_runtime_file(self._runtime_dir, self.spec, self._secret) - _register_atexit_cleanup_handler(self._runtime_file_path) + _register_atexit_cleanup_handler(self._runtime_file_path, self._created_dirs) with ACTIVE_CLEANUPS_LOCK: ACTIVE_CLEANUPS.append(self.cleanup) return self._runtime_file_path @@ -356,8 +370,8 @@ def cleanup(self) -> None: if self._runtime_file_path: logger.debug(f'Cleaning up runtime file: {self._runtime_file_path}') - _ = _remove_file(self._runtime_file_path) + _ = _remove_file(self._runtime_file_path, self._created_dirs) self._runtime_file_path = None else: # lazy_write: the directory exists but no file was ever written. - _remove_empty_runtime_dirs(self._runtime_dir) + _remove_empty_dirs(self._created_dirs) diff --git a/packages/genkit/tests/genkit/veneer/server_test.py b/packages/genkit/tests/genkit/veneer/server_test.py index 26e4b40a5..1715f8ae4 100644 --- a/packages/genkit/tests/genkit/veneer/server_test.py +++ b/packages/genkit/tests/genkit/veneer/server_test.py @@ -118,9 +118,19 @@ def test_runtime_manager_removes_empty_runtime_dirs(tmp_path: pathlib.Path) -> N def test_runtime_manager_keeps_dirs_with_other_files(tmp_path: pathlib.Path) -> None: runtime_dir = tmp_path / '.genkit' / 'runtimes' - runtime_dir.mkdir(parents=True) + (tmp_path / '.genkit').mkdir() (tmp_path / '.genkit' / 'traces.json').write_text('{}') with RuntimeManager(spec=ServerSpec(port=3100), runtime_dir=runtime_dir): pass assert not runtime_dir.exists() assert (tmp_path / '.genkit' / 'traces.json').exists() + + +def test_runtime_manager_keeps_runtime_dir_the_cli_created(tmp_path: pathlib.Path) -> None: + """`genkit start` creates and watches `.genkit/runtimes`; removing it blinds the watcher.""" + runtime_dir = tmp_path / '.genkit' / 'runtimes' + runtime_dir.mkdir(parents=True) + with RuntimeManager(spec=ServerSpec(port=3100), runtime_dir=runtime_dir) as rm: + path = rm.write_runtime_file() + assert not path.exists() + assert runtime_dir.is_dir() From 2f69a27908e163e6e9ee7403a3628a98ff64d9dc Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 20:14:27 -0600 Subject: [PATCH 7/8] style(py): format runtime and reflection modules --- packages/genkit/src/genkit/_ai/_runtime.py | 2 ++ packages/genkit/src/genkit/_core/_reflection.py | 4 +--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_runtime.py b/packages/genkit/src/genkit/_ai/_runtime.py index 21c87a52b..1e6f0fa02 100644 --- a/packages/genkit/src/genkit/_ai/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_runtime.py @@ -65,6 +65,8 @@ def find_project_root(start: Path | None = None) -> Path: return current current = current.parent return cwd + + ACTIVE_CLEANUPS: list[Callable[[], None]] = [] # RLock so a SIGINT/SIGTERM mid-update can re-enter: signal handlers run on the # main thread, and a plain Lock would deadlock if that thread already holds it. diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index f0887638e..d4d0592af 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -254,9 +254,7 @@ def _warn_on_spec_version_mismatch(spec_version: object) -> None: if spec_version == _REFLECTION_API_SPEC_VERSION: return if not isinstance(spec_version, int | float) or spec_version < _REFLECTION_API_SPEC_VERSION: - logger.warning( - 'WARNING: Genkit CLI version may be outdated. Please update `genkit-cli` to the latest version.' - ) + logger.warning('WARNING: Genkit CLI version may be outdated. Please update `genkit-cli` to the latest version.') else: logger.warning( 'Genkit CLI is newer than runtime library. Some feature may not be supported. ' From 3412771c212154248424a7e00bd6c442fb87d113 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 21:20:28 -0600 Subject: [PATCH 8/8] fix(py): scope value overwrite, Dev UI trace flush, and stderr logging - Keep duplicate checks on Registry.register_value by default and opt in from define_value only, so duplicate middleware or format names still raise ValueError. - Flush flush_developer_ui_collector instead of flush_instrumentations in reflection v1 outside the action try/except, isolating remote OTel exporters and preventing collector errors from failing completed runs. - Route Genkit's unconfigured console logs to dynamic sys.stderr on ExportTee without mutating structlog's global logger_factory. --- packages/genkit/src/genkit/_ai/_aio.py | 2 +- packages/genkit/src/genkit/_core/_logger.py | 86 +++++++++--- .../genkit/src/genkit/_core/_reflection.py | 130 +++++++++--------- .../genkit/src/genkit/_core/_reflection_v2.py | 6 +- packages/genkit/src/genkit/_core/_registry.py | 21 ++- .../src/genkit/_core/_telemetry/_http.py | 7 +- .../core/developer_ui_handshake_test.py | 19 +++ .../genkit/core/endpoints/reflection_test.py | 95 +++++++++++-- .../genkit/tests/genkit/core/logger_test.py | 45 ++++++ .../genkit/tests/genkit/core/registry_test.py | 8 ++ .../genkit/tests/genkit/veneer/lookup_test.py | 78 +++++++++++ 11 files changed, 394 insertions(+), 103 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 20e019d5e..ee1df7055 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -726,7 +726,7 @@ def define_value(self, *, kind: str, name: str, value: object) -> None: raise ValueError(f'define_value kind {kind!r} is reserved; use {_CORE_VALUE_KINDS[kind]} instead.') if value is None: raise ValueError('define_value value must not be None; lookup_value returns None for "not defined".') - self._registry.register_value(kind, name, value) + self._registry.register_value(kind, name, value, allow_overwrite=True) # Overload 1: Both input_schema and output_schema typed -> Prompt[InputT, OutputT] @overload diff --git a/packages/genkit/src/genkit/_core/_logger.py b/packages/genkit/src/genkit/_core/_logger.py index f338b1b73..f8ae00048 100644 --- a/packages/genkit/src/genkit/_core/_logger.py +++ b/packages/genkit/src/genkit/_core/_logger.py @@ -82,6 +82,34 @@ def unrecognized_level() -> str | None: return raw +_DEFAULT_STRUCTLOG_FACTORY: object = ( + structlog.get_config().get('logger_factory') + if not structlog.is_configured() + else getattr(getattr(structlog, '_config', None), '_BUILTIN_DEFAULT_LOGGER_FACTORY', None) +) + +_stderr_lock = threading.Lock() + + +class _StderrPrintLogger: + """structlog ``PrintLogger`` equivalent that resolves ``sys.stderr`` at emit time. + + Passing ``file=sys.stderr`` to ``structlog.PrintLoggerFactory`` binds the + stream object once at factory creation, missing later ``sys.stderr`` swaps + from ``pytest`` capture, ``contextlib.redirect_stderr``, or notebooks. + """ + + def msg(self, message: object) -> None: + with _stderr_lock: + stream = sys.stderr + if stream is not None: + stream.write(f'{message}\n') + stream.flush() + + log = debug = info = warn = warning = msg + fatal = failure = err = error = critical = exception = msg + + def _app_chose_level() -> bool: """Report whether the application configured structlog with a level of its own.""" if not structlog.is_configured(): @@ -90,6 +118,13 @@ def _app_chose_level() -> bool: return structlog.get_config().get('wrapper_class') is not unfiltered +def _app_chose_logger_factory() -> bool: + """Report whether the application configured structlog with its own logger factory.""" + if not structlog.is_configured(): + return False + return structlog.get_config().get('logger_factory') is not _DEFAULT_STRUCTLOG_FACTORY + + def configure_structlog_level() -> bool: """Apply ``GENKIT_LOG`` to structlog unless the application chose a level. @@ -103,16 +138,7 @@ def configure_structlog_level() -> bool: """ if _app_chose_level(): return False - if structlog.is_configured(): - structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(resolve_level())) - else: - # structlog's default factory prints to stdout, which corrupts - # `python cli.py | jq .`. Logs go to stderr; an app that already - # picked a logger factory keeps it. - structlog.configure( - wrapper_class=structlog.make_filtering_bound_logger(resolve_level()), - logger_factory=structlog.PrintLoggerFactory(file=sys.stderr), - ) + structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(resolve_level())) ignored = unrecognized_level() if ignored is not None: get_logger(__name__).warning( @@ -238,31 +264,53 @@ class ExportTee: above, so a quiet terminal can still fill the trace viewer's log panel. """ - def __init__(self, bound: BindableLogger, attrs: dict[str, object] | None = None) -> None: + def __init__( + self, + bound: BindableLogger, + attrs: dict[str, object] | None = None, + *, + stderr_bound: BindableLogger | None = None, + ) -> None: self._bound = bound + self._stderr_bound = stderr_bound self._attrs = attrs or {} + def _active_bound(self) -> BindableLogger: + if self._stderr_bound is not None and not _app_chose_logger_factory(): + return self._stderr_bound + return self._bound + def bind(self, **new_values: object) -> ExportTee: - return ExportTee(self._bound.bind(**new_values), attrs={**self._attrs, **new_values}) + stderr = self._stderr_bound.bind(**new_values) if self._stderr_bound is not None else None + return ExportTee(self._bound.bind(**new_values), attrs={**self._attrs, **new_values}, stderr_bound=stderr) def unbind(self, *keys: str) -> ExportTee: kept = {k: v for k, v in self._attrs.items() if k not in keys} - return ExportTee(self._bound.unbind(*keys), attrs=kept) + stderr = self._stderr_bound.unbind(*keys) if self._stderr_bound is not None else None + return ExportTee(self._bound.unbind(*keys), attrs=kept, stderr_bound=stderr) def try_unbind(self, *keys: str) -> ExportTee: kept = {k: v for k, v in self._attrs.items() if k not in keys} - return ExportTee(self._bound.try_unbind(*keys), attrs=kept) + stderr = self._stderr_bound.try_unbind(*keys) if self._stderr_bound is not None else None + return ExportTee(self._bound.try_unbind(*keys), attrs=kept, stderr_bound=stderr) def new(self, **new_values: object) -> ExportTee: - return ExportTee(self._bound.new(**new_values), attrs=dict(new_values)) + bound_new = self._bound.new(**new_values) + stderr = ( + cast(BindableLogger, structlog.wrap_logger(_StderrPrintLogger())).bind(**new_values) + if self._stderr_bound is not None + else None + ) + return ExportTee(bound_new, attrs=dict(new_values), stderr_bound=stderr) def is_enabled_for(self, level: int) -> bool: from genkit._core._telemetry._log_exporter import log_export_is_enabled if level >= logging.DEBUG and log_export_is_enabled(): return True + active = self._active_bound() for attr in ('is_enabled_for', 'isEnabledFor'): - check = getattr(self._bound, attr, None) + check = getattr(active, attr, None) if not callable(check): continue try: @@ -277,7 +325,7 @@ def _emit(self, level: int, event: str, args: tuple[object, ...], kw: dict[str, emit_log(level=level, event=_interpolate_event(event, args), attrs={**self._attrs, **kw}) def __getattr__(self, name: str) -> object: - target = getattr(self._bound, name) + target = getattr(self._active_bound(), name) if name == 'log' and callable(target): def emit_log(level: int, event: str, *args: object, **kw: object) -> object: @@ -381,7 +429,9 @@ async def lookup_menu(restaurant_id: str) -> int: return 12 ``` """ - return cast(GenkitLogger, ExportTee(structlog.get_logger(name))) + app_bound = structlog.get_logger(name) if name is not None else structlog.get_logger() + stderr_bound = cast(BindableLogger, structlog.wrap_logger(_StderrPrintLogger())) + return cast(GenkitLogger, ExportTee(app_bound, stderr_bound=stderr_bound)) def is_debug_enabled(logger: GenkitLogger) -> bool: diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index d4d0592af..2ca30fc0d 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -49,8 +49,7 @@ from genkit._core._model import AgentInit, AgentInput, ModelRef from genkit._core._reflection_config import REFLECTION_SECRET_HEADER, secrets_equal from genkit._core._registry import Registry -from genkit._core._telemetry._http import connect_developer_ui_collector -from genkit._core._telemetry._instrumentation import flush_instrumentations +from genkit._core._telemetry._http import connect_developer_ui_collector, flush_developer_ui_collector from genkit._core._telemetry._log_exporter import enable_log_export logger = get_logger(__name__) @@ -130,70 +129,75 @@ async def on_trace_start(self, tid: str, sid: str) -> None: async def execute(self) -> None: try: - on_chunk = ( - ( - lambda c: self.queue.put_nowait( - ( - c.model_dump_json(by_alias=True, exclude_none=True) - if isinstance(c, BaseModel) - else json.dumps(c) + try: + on_chunk = ( + ( + lambda c: self.queue.put_nowait( + ( + c.model_dump_json(by_alias=True, exclude_none=True) + if isinstance(c, BaseModel) + else json.dumps(c) + ) + + '\n' ) - + '\n' ) + if self.stream + else None ) - if self.stream - else None - ) - # A bidi action's fn already gives a single-turn view of a connection - # when driven through _run() (seed one input, stream chunks, return the - # output), so the HTTP path just needs _run(). The only bidi-specific - # step is normalizing the agent payload: minting a session id for a - # server-store agent and defaulting an absent turn to an empty input. - input_val = self.payload.get('input') - init = None - if isinstance(self.action, BidiAction): - init = resolve_agent_init(self.action, self.payload.get('init')) - if input_val is None: - input_val = AgentInput() - else: - input_val = AgentInput.model_validate(as_agent_input_dict(input_val)) - - output = await self.action._run( - input=input_from_json(input_val), - on_chunk=on_chunk, - context=self.payload.get('context', {}), - on_trace_start=self.on_trace_start, - telemetry_labels=self.payload.get('telemetryLabels'), - init=init, - ) - result = ( - output.response.model_dump(by_alias=True, exclude_none=True) - if isinstance(output.response, BaseModel) - else output.response - ) - payload: dict[str, Any] = {'result': result} - if output.trace_id: - payload['telemetry'] = {'traceId': output.trace_id, 'spanId': output.span_id} - # Export the root span before answering, as v2 and JS do, so the - # Dev UI trace view is complete when the response lands. - await asyncio.to_thread(flush_instrumentations) - self.queue.put_nowait(json.dumps(payload)) - except asyncio.CancelledError: - raise - except (Exception, Interrupt) as e: - # A tool run on its own has no generate loop to pause, so its - # Interrupt is reported like any other failure. - # Dev UI already shows the error + stack from the reflection response. - # Dumping a full traceback here turns every playground failure into - # terminal noise. - logger.debug('Action failed: %s: %s', type(e).__name__, e, exc_info=True) - error = get_reflection_json(interrupt_escape_error(e) or e, trace_id=self.trace_id) - if error.details is not None and not error.details.stack and e.__traceback__: - # Same as v2: `genkit flow:run` prints this, so give it Python frames. - stack = ''.join(traceback.format_exception(type(e), e, e.__traceback__)) - error = error.model_copy(update={'details': error.details.model_copy(update={'stack': stack})}) - await asyncio.to_thread(flush_instrumentations) - self.queue.put_nowait(json.dumps({'error': error.model_dump(by_alias=True)})) + # A bidi action's fn already gives a single-turn view of a connection + # when driven through _run() (seed one input, stream chunks, return the + # output), so the HTTP path just needs _run(). The only bidi-specific + # step is normalizing the agent payload: minting a session id for a + # server-store agent and defaulting an absent turn to an empty input. + input_val = self.payload.get('input') + init = None + if isinstance(self.action, BidiAction): + init = resolve_agent_init(self.action, self.payload.get('init')) + if input_val is None: + input_val = AgentInput() + else: + input_val = AgentInput.model_validate(as_agent_input_dict(input_val)) + + output = await self.action._run( + input=input_from_json(input_val), + on_chunk=on_chunk, + context=self.payload.get('context', {}), + on_trace_start=self.on_trace_start, + telemetry_labels=self.payload.get('telemetryLabels'), + init=init, + ) + result = ( + output.response.model_dump(by_alias=True, exclude_none=True) + if isinstance(output.response, BaseModel) + else output.response + ) + payload: dict[str, Any] = {'result': result} + if output.trace_id: + payload['telemetry'] = {'traceId': output.trace_id, 'spanId': output.span_id} + response_json = json.dumps(payload) + except asyncio.CancelledError: + raise + except (Exception, Interrupt) as e: + # A tool run on its own has no generate loop to pause, so its + # Interrupt is reported like any other failure. + # Dev UI already shows the error + stack from the reflection response. + # Dumping a full traceback here turns every playground failure into + # terminal noise. + logger.debug('Action failed: %s: %s', type(e).__name__, e, exc_info=True) + error = get_reflection_json(interrupt_escape_error(e) or e, trace_id=self.trace_id) + if error.details is not None and not error.details.stack and e.__traceback__: + # Same as v2: `genkit flow:run` prints this, so give it Python frames. + stack = ''.join(traceback.format_exception(type(e), e, e.__traceback__)) + error = error.model_copy(update={'details': error.details.model_copy(update={'stack': stack})}) + response_json = json.dumps({'error': error.model_dump(by_alias=True)}) + + try: + # Export the root span before answering, as v2 and JS do, so the + # Dev UI trace view is complete when the response lands. + await asyncio.to_thread(flush_developer_ui_collector) + except Exception as e: + logger.debug('Failed to flush Developer UI trace collector: %s', e) + self.queue.put_nowait(response_json) finally: self.trace_ready.set() self.queue.put_nowait(None) diff --git a/packages/genkit/src/genkit/_core/_reflection_v2.py b/packages/genkit/src/genkit/_core/_reflection_v2.py index 4fe14279a..d92b0d286 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -447,7 +447,10 @@ async def handle_end_input_stream(self, req_id: str | int | None, params: dict[s stream.close() async def flush_tracing(self) -> None: - await asyncio.to_thread(flush_developer_ui_collector) + try: + await asyncio.to_thread(flush_developer_ui_collector) + except Exception as e: + logger.debug('Failed to flush Developer UI trace collector: %s', e) @staticmethod def run_action_call_options( @@ -538,6 +541,7 @@ async def send_run_action_error( message=coerce_json_rpc_message(ref.message), details=ReflectionErrorDetails(stack=stack, trace_id=tid) if (stack or tid) else None, ) + await self.flush_tracing() await self.send_error( sid, JSON_RPC_SERVER_ERROR, diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 8034fdb2f..b4663f298 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -454,27 +454,40 @@ async def list_actions( parent_catalog = await self._parent.list_actions(dap_timeout_seconds=dap_timeout_seconds) return {**parent_catalog, **catalog} - def register_value(self, kind: str, name: str, value: object) -> None: + def register_value( + self, + kind: str, + name: str, + value: object, + *, + allow_overwrite: bool = False, + ) -> None: """Registers a value with a given kind and name. This method stores a value in a nested dictionary, where the first level is keyed by the 'kind' and the second level is keyed by the 'name'. - It prevents duplicate registrations for the same kind and name. + It prevents duplicate registrations for the same kind and name unless + ``allow_overwrite`` is set. Args: kind: The kind of the value (e.g., "format", "default-model"). name: The name of the value (e.g., "json", "text"). value: The value to be registered. Can be of any non-serializable type. + allow_overwrite: Replace an existing value under the same kind and + name instead of raising. - Registering the same kind and name again replaces the value. + Raises: + ValueError: If ``allow_overwrite`` is ``False`` and a value with the + given kind and name is already registered. """ with self._lock: if kind not in self._value_by_kind_and_name: self._value_by_kind_and_name[kind] = {} if name in self._value_by_kind_and_name[kind]: - # Re-running a notebook cell re-registers; overwrite like flows/tools do. + if not allow_overwrite: + raise ValueError(f'value for kind "{kind}" and name "{name}" is already registered') logger.debug(f'Overwriting value for kind "{kind}" and name "{name}"') self._value_by_kind_and_name[kind][name] = value diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index d852c6993..a41a1b5ad 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -363,9 +363,12 @@ def flush_developer_ui_collector() -> None: APM backends (``GenAiInstrumentation``, Cloud Trace, custom providers) stay isolated from interactive Dev UI clicks. """ - for inst in instrumentations: + for inst in list(instrumentations): if isinstance(inst, DirectHttpInstrumentation): - inst.flush() + try: + inst.flush() + except Exception as e: + logger.debug('Failed to flush Developer UI trace collector: %s', e) def maybe_inject_dev_instrumentation() -> None: diff --git a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py index 1a203cb5a..3182aace8 100644 --- a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py +++ b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py @@ -328,3 +328,22 @@ def flush(self) -> None: assert dev_sink.flushes == 1 assert remote.flushes == 0 + + +@pytest.mark.asyncio +async def test_dev_ui_run_flush_ignores_broken_collector_sink() -> None: + """A raising Dev UI collector sink does not fail reflection v2 flush_tracing.""" + + class BrokenSink: + def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + pass + + def flush(self) -> None: + raise OSError('collector closed') + + def shutdown(self) -> None: + pass + + configure_instrumentation(DevUIInstrumentation(BrokenSink())) # type: ignore[arg-type] + + await _handshake_server().flush_tracing() diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py index cd7db0bfc..1c3853734 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py @@ -622,25 +622,92 @@ async def order(order_id: str) -> str: @pytest.mark.asyncio -async def test_run_action_flushes_spans_before_responding(monkeypatch: pytest.MonkeyPatch) -> None: - """v1 matches v2: the root span is exported by the time the response lands.""" - from genkit._core import _reflection +async def test_run_action_flushes_dev_ui_collector_only() -> None: + """v1 flushes DevUIInstrumentation before responding and leaves remote backends untouched.""" + from genkit._core._telemetry._http import DevUIInstrumentation + from genkit._core._telemetry._instrumentation import configure_instrumentation, reset_instrumentation events: list[str] = [] - monkeypatch.setattr(_reflection, 'flush_instrumentations', lambda: events.append('flush')) - ai = Genkit() - @ai.flow() - async def order_dish(dish: str) -> str: - events.append('run') - return dish + class RecordingSink: + def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + pass - app = create_reflection_asgi_app(ai._registry) - async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: - response = await client.post('/api/runAction', json={'key': '/flow/order_dish', 'input': 'Tartine'}) + def flush(self) -> None: + events.append('dev_flush') - assert response.status_code == 200 - assert events == ['run', 'flush'] + def shutdown(self) -> None: + pass + + class SlowRemoteBackend: + async def run_in_new_span(self, metadata: Any, next: Any) -> Any: # noqa: ANN401 + return await next(MagicMock()) + + def flush(self) -> None: + events.append('remote_flush') + raise RuntimeError('remote exporter timed out') + + reset_instrumentation() + try: + configure_instrumentation(DevUIInstrumentation(RecordingSink())) # type: ignore[arg-type] + configure_instrumentation(SlowRemoteBackend()) + ai = Genkit() + + @ai.flow() + async def order_dish(dish: str) -> str: + events.append('run') + return dish + + app = create_reflection_asgi_app(ai._registry) + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + response = await client.post('/api/runAction', json={'key': '/flow/order_dish', 'input': 'Tartine'}) + + assert response.status_code == 200 + assert response.json()['result'] == 'Tartine' + assert events == ['run', 'dev_flush'] + finally: + reset_instrumentation() + + +@pytest.mark.asyncio +async def test_run_action_succeeds_when_dev_ui_collector_flush_raises() -> None: + """A broken Dev UI trace collector flush does not turn a completed action into an error response.""" + from genkit._core._telemetry._http import DevUIInstrumentation + from genkit._core._telemetry._instrumentation import configure_instrumentation, reset_instrumentation + + class BrokenSink: + def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + pass + + def flush(self) -> None: + raise OSError('collector unreachable') + + def shutdown(self) -> None: + pass + + reset_instrumentation() + try: + configure_instrumentation(DevUIInstrumentation(BrokenSink())) # type: ignore[arg-type] + ai = Genkit() + + @ai.flow() + async def order_dish(dish: str) -> str: + return dish + + @ai.flow() + async def fail_dish(dish: str) -> str: + raise ValueError(f'sold out: {dish}') + + app = create_reflection_asgi_app(ai._registry) + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + ok_resp = await client.post('/api/runAction', json={'key': '/flow/order_dish', 'input': 'Tartine'}) + err_resp = await client.post('/api/runAction', json={'key': '/flow/fail_dish', 'input': 'Tartine'}) + + assert ok_resp.status_code == 200 + assert ok_resp.json()['result'] == 'Tartine' + assert 'sold out: Tartine' in err_resp.json()['error']['message'] + finally: + reset_instrumentation() @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/logger_test.py b/packages/genkit/tests/genkit/core/logger_test.py index ef066f606..56b244be4 100644 --- a/packages/genkit/tests/genkit/core/logger_test.py +++ b/packages/genkit/tests/genkit/core/logger_test.py @@ -492,3 +492,48 @@ def test_configure_structlog_level_keeps_app_logger_factory() -> None: with mock.patch.dict(os.environ, clear=True): assert configure_structlog_level() is True assert structlog.get_config()['logger_factory'] is factory + + +@pytest.mark.usefixtures('_restore_structlog') +def test_unconfigured_app_structlog_stays_on_stdout(capsys: pytest.CaptureFixture[str]) -> None: + """Configuring Genkit logging leaves an unconfigured host app's structlog.get_logger() on stdout.""" + structlog.reset_defaults() + with mock.patch.dict(os.environ, clear=True): + configure_logging() + structlog.get_logger('host.app').info('order accepted') + get_logger('genkit.flow').info('span exported') + + captured = capsys.readouterr() + assert 'order accepted' in captured.out + assert 'order accepted' not in captured.err + assert 'span exported' in captured.err + assert 'span exported' not in captured.out + + +@pytest.mark.usefixtures('_restore_structlog') +def test_genkit_logger_follows_late_stderr_swap(monkeypatch: pytest.MonkeyPatch) -> None: + """Swapping sys.stderr after configure_logging and get_logger redirects subsequent Genkit log lines.""" + import contextlib + import io + + structlog.reset_defaults() + first_err = io.StringIO() + second_err = io.StringIO() + third_err = io.StringIO() + + with mock.patch.dict(os.environ, clear=True): + monkeypatch.setattr('sys.stderr', first_err) + configure_logging() + logger = get_logger('genkit.orders') + logger.info('first turn') + + monkeypatch.setattr('sys.stderr', second_err) + logger.info('second turn') + + with contextlib.redirect_stderr(third_err): + logger.info('notebook cell') + + assert 'first turn' in first_err.getvalue() + assert 'second turn' not in first_err.getvalue() + assert 'second turn' in second_err.getvalue() + assert 'notebook cell' in third_err.getvalue() diff --git a/packages/genkit/tests/genkit/core/registry_test.py b/packages/genkit/tests/genkit/core/registry_test.py index 0e88bc962..bed9f87a4 100644 --- a/packages/genkit/tests/genkit/core/registry_test.py +++ b/packages/genkit/tests/genkit/core/registry_test.py @@ -194,6 +194,14 @@ def test_register_value() -> None: assert registry.lookup_value('format', 'json') == [1, 2, 3] + with pytest.raises(ValueError, match='value for kind "format" and name "json" is already registered'): + registry.register_value('format', 'json', [4, 5, 6]) + + assert registry.lookup_value('format', 'json') == [1, 2, 3] + + registry.register_value('format', 'json', [4, 5, 6], allow_overwrite=True) + assert registry.lookup_value('format', 'json') == [4, 5, 6] + @pytest.mark.asyncio async def test_trigger_lazy_loading_reentrant_guard() -> None: diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index 6cd6b8423..e1048f2dd 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -209,6 +209,84 @@ class DishV2(BaseModel): assert ai._registry.lookup_schema_type('Dish') is DishV2 +@pytest.mark.asyncio +async def test_duplicate_middleware_registration_raises() -> None: + """Middleware collisions raise instead of letting the last registration silently win.""" + + class PluginRetry(Middleware): + name = 'retry' + description = 'Plugin retry middleware.' + + async def wrap_model( + self, + params: ModelHookParams, + ctx: MiddlewareContext, + next_fn: NextModel, + ) -> ModelResponse: + res = await next_fn(params, ctx) + return _answer(f'plugin:{res.text}') + + class AppRetry(Middleware): + name = 'retry' + description = 'Conflicting app retry middleware.' + + class MiddlewarePlugin(Plugin): + def __init__(self, plugin_name: str, mw_cls: type[Middleware]) -> None: + self.name = plugin_name + self._mw_cls = mw_cls + + async def init(self) -> list[Action]: + return [] + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + return None + + async def list_actions(self) -> list[Action]: + return [] + + def list_middleware(self) -> list[type[Middleware]]: + return [self._mw_cls] + + with pytest.raises(ValueError, match='value for kind "middleware" and name "retry" is already registered'): + Genkit(plugins=[MiddlewarePlugin('first-mw', PluginRetry), MiddlewarePlugin('second-mw', AppRetry)]) + + ai = Genkit(plugins=[MiddlewarePlugin('first-mw', PluginRetry)]) + _define_answering_model(ai, 'kitchen', 'salmon') + + with pytest.raises(ValueError, match='value for kind "middleware" and name "retry" is already registered'): + ai.define_middleware(AppRetry) + + util = await ai._registry.resolve_action(ActionKind.UTIL, 'generate') # pyright: ignore[reportPrivateUsage] + assert util is not None + out = await util.run( + GenerateActionOptions( + model='kitchen', + messages=[Message(role=Role.USER, content=[Part.from_text('dish?')])], + use=[MiddlewareRef(name='retry')], + ) + ) + assert out.response.text == 'plugin:salmon' + + +def test_duplicate_format_registration_raises() -> None: + """Registering a format under an existing name raises instead of overwriting.""" + from genkit.formats import FormatHandler, Formatter, FormatterConfig + + class DuplicateJsonFormat(Formatter): + def __init__(self) -> None: + super().__init__('json', FormatterConfig(content_type='application/json')) + + def handle(self, schema: dict[str, object] | None) -> FormatHandler[str, str]: + return FormatHandler( + message_parser=lambda msg: msg.text, + chunk_parser=lambda chunk: chunk.text, + ) + + ai = Genkit() + with pytest.raises(ValueError, match='value for kind "format" and name "json" is already registered'): + ai.define_format(DuplicateJsonFormat()) + + def test_define_value_requires_keywords() -> None: """`ai.define_value('k', 'n', v)` raises TypeError, so swapped kind and name can't store under the wrong key.""" ai = Genkit()