Skip to content

Modernize the mu-python-template - #39

Open
nvdk wants to merge 36 commits into
masterfrom
feature/semantic-ai-fixes
Open

nvdk wants to merge 36 commits into
masterfrom
feature/semantic-ai-fixes

Conversation

@nvdk

@nvdk nvdk commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Modernizes the template for the 2.0.0 release: a supported Python and server, thread-safe helpers, mu-authorization support and pinned dependencies.

Server & base image

  • Replace the deprecated tiangolo/meinheld-gunicorn:python3.8 base image with python:3.13-slim, running gunicorn with threaded (gthread) workers. Behaviour is unchanged: 1 worker (WEB_CONCURRENCY) handling one request at a time. Other gunicorn settings can be passed through GUNICORN_CMD_ARGS, e.g. --threads 4.
  • New DEV_SERVER=gunicorn for development mode: the production server with live reload, e.g. to test behaviour with multiple workers or threads. The Flask development server (with debugger) stays the default.
  • on-build.sh hook, in line with the other templates: services can install system packages before their Python requirements are installed. gcc and g++ are included for packages without wheels.
  • Dependencies are pinned and installed with uv. Added a .dockerignore.
  • CI builds linux/arm64 next to amd64 for releases, latest and feature branches.
  • Breaking: logs are written to stdout only, /logs is no longer used.
  • Breaking: some environment variables of the meinheld-gunicorn-docker image (MODULE_NAME, APP_MODULE, GUNICORN_CONF, WORKERS_PER_CORE, …) are no longer supported (as far as we know they weren't used). Use WEB_CONCURRENCY, HOST, PORT, BIND and GUNICORN_CMD_ARGS instead.

Helpers

  • Thread safety: query() and update() execute on a copy of the shared SPARQLWrapper instances. Configuration set on the shared instances (timeouts, custom headers) still applies to every query.
  • mu-authorization support: new keyword-only sudo and scope arguments. Sudo queries must be enabled per container with ALLOW_MU_AUTH_SUDO, DEFAULT_MU_AUTH_SCOPE sets a fallback scope.
  • The mu headers of the current request are forwarded automatically. The helpers also work outside a request (startup code, background threads).
  • The mu-auth-allowed-groups and mu-auth-used-groups headers returned by mu-authorization are forwarded to the client, and the resolved groups are reused for later queries within the same request.
  • update() returns the SPARQLWrapper QueryResult.
  • New BaseHTTPException: raise it anywhere in a handler to return a JSON:API error response. Breaking: validate_json_api_content_type and validate_resource_type raise it instead of returning an error response. Returning their result from a route keeps working.
  • New sparql_escape_decimal.
  • sparql_escape now escapes True/False as xsd:boolean instead of xsd:integer.
  • An unsupported LOG_LEVEL raises an error at startup.
  • Breaking: the deprecated update_modified helper was removed.

Deprecations

Logged once per feature, can be turned off with PRINT_DEPRECATION_WARNINGS=false.

  • Using helpers and sparql_escape without importing them.
  • app.before_first_request: brought back for services written against older Flask versions, but deprecated in favour of startup code at the top level of web.py.

Compatibility

Python 3.13, Flask 3.1, SPARQLWrapper 2.0, rdflib 7.6, gunicorn 26.2. Pinned dependencies of services might need an update.

Tested

  • Verified against a real service (catalog-harvester): builds, boots and behaves like v2.0.0-beta.3.
  • Smoke-tested against sparql-parser 0.0.15 and Virtuoso 1.4.0 with a child service:
    • ONBUILD installs the child's requirements.
    • Normal, sudo and mixed queries return the expected data, and mu-auth-allowed-groups is forwarded to the client.
    • A crashing route returns a 500 and logs a full traceback.
    • A missing module stops the container at startup with the ModuleNotFoundError.
    • Development mode reloads on changes with both DEV_SERVER=flask and DEV_SERVER=gunicorn.

Closes #12, closes #14, closes #18, closes #19, closes #28, closes #33, closes #34, closes #36, closes #37

madnificent and others added 17 commits October 1, 2026 01:01
This is a first step.  It's not fully tested.  It doesn't keep the full API
space of the previous parent's internals but it does keep the features we know
are used in the wild.

Needs testing.
…d expand minimally with some much needed compilers

(cherry picked from commit 5fba2e5)
(cherry picked from commit 3063183)
(cherry picked from commit da5fa38)
… parts of the helper function, so we don't need to be backward compatible with them

(cherry picked from commit 81c7dbb)
…port for providing scope, wait_for_triplestore no longer does a sudo query to not break non-sudo services

(cherry picked from commit 8533639)
…th an example implementation services could use while waiting for the real deal

(cherry picked from commit d02fbb6)
Raising a BaseHTTPException results in a JSONAPI error response. It is
available without import and takes the same arguments as in the FastAPI
based semantic-ai/mu-python-template. A sudo query without permission
raises it with status 403.

Co-authored-by: Joachim van der Herten <joachim@ml2grow.com>
Services may configure helpers.sparqlQuery and helpers.sparqlUpdate (e.g. a
timeout or custom headers such as mu-auth-sudo), which earlier versions of
the template applied to every query. Copying those per query keeps that
working while staying thread-safe. As every query starts from a copy, the
sudo and scope headers no longer need to be cleared.
- validate_resource_type compared strings by identity, rejecting valid
  resource types
- validate_json_api_content_type crashed on requests without Content-Type
- update_modified used the time the service started as default date
The Uvicorn worker sizes its WSGI thread pool with gunicorn's threads
setting (default 1, e.g. GUNICORN_CMD_ARGS="--threads 4"), so a worker
handles one request at a time like with meinheld. It also stops when
gunicorn's reloader requests so, which Uvicorn didn't check. The
uvicorn-worker package replaces the deprecated uvicorn.workers module.

DEV_SERVER=gunicorn runs the production server with live-reloading in
development mode. app.before_first_request, removed in Flask 2.3, is
emulated with a deprecation warning.
Co-authored-by: Joachim van der Herten <joachim@ml2grow.com>
Co-authored-by: karel kremer <karel.kremer@redpencil.io>
@nvdk
nvdk requested a review from madnificent October 26, 2026 15:41
@nvdk

nvdk commented Oct 26, 2026

Copy link
Copy Markdown
Member Author

I will also remove the logs being written to a file, since that's not in-line with other templates. If you want to keep logs this can be done through docker.

@nvdk nvdk self-assigned this Oct 27, 2026
Niels V added 6 commits October 27, 2026 08:31
Other templates only write to stdout and logs are available through stdout. Removing this for consistency.
Log files require management and it's easiest if this is done in one place (through docker logs)
to keep .git and CI config out of the image
In line with the js template. Allowed groups resolved by
mu-authorization are stored per request and forwarded to the client.
uv is a fast, pip-compatible installer. The pip-style interface is used
with --system: no virtual environments (the container provides the
isolation)
Comment thread gunicorn_worker.py Outdated
from uvicorn_worker import UvicornWorker


class UvicornWSGIWorker(UvicornWorker):

@javdrher javdrher Nov 18, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As a general comment, why the choice to run Uvicorn which is an ASGI webserver as worker for Gunicorn, a WSGI webserver? Flask is a WSGI framework hence inside the ASGI worker it needs to be wrapped again in the WSGI middleware.

start.sh can then simply run:
gunicorn --reload -k gthread -c /gunicorn_conf.py web:app and this entire file can be deleted.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

based on a chat conversation: do note that Flask is always sync. Even if you start using async handlers in Flask, in the end they run in an eventloop which is then run synchronously. The webapp therefor always runs on top of a WSGI webserver framework, if you bring an ASGI webserver you need the middleware to convert it (basically running the webapp in a threadpool so it becomes async again).

Comment thread helpers.py Resolved
Comment thread helpers.py Resolved
Comment thread helpers.py
@@ -24,6 +25,8 @@
"""

MU_APPLICATION_GRAPH = os.environ.get('MU_APPLICATION_GRAPH')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In general: these global dependencies on the environment with no defaults make testing harder.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

a fair remark,but can perhaps be deferred to a separate PR?

Comment thread helpers.py Resolved
Comment thread web.py Outdated
builtins.app = app
builtins.helpers = helpers
builtins.sparql_escape = sparql_escape
builtins.BaseHTTPException = BaseHTTPException

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

these things are there for backward compatibility but should be removed, regardless if it breaks anything or not and definitely not be expanded.

  1. Every module in the worker, including third-party libraries, sees app, helpers, sparql_escape, BaseHTTPException as builtins. A dependency that happens to use any of these names as a variable now has different behavior inside this container than anywhere else. That's a debugging nightmare that will be attributed to anything but the template.

  2. any tooling such as mypy, ruff, pyright, pylint,... which are usually included for validation in CI are left broken because of this.

  3. Any local variable named app or helpers in a service function shadows the builtin in that scope only. The service works until a refactor moves a line out of the function, then breaks with NameError/AttributeError far from the cause. And because helpers is both a real importable module and a builtin, import helpers vs. ambient helpers can even resolve to different objects in edge cases with reloads.

  4. it makes automated testing reliant on executing web.py's side effects.

  5. for developers its super confusing.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for bringing this to my attention, we had a similar thing in the ruby template so I took a similar approach here:

  • BaseHTTPException is no longer a builtin, since it's new. it has to be imported from helpers.
  • Using helpers or sparql_escape without an import still works, but logs a deprecation warning (once per helper, can be turned off with PRINT_DEPRECATION_WARNINGS). Services that import explicitly shadow the builtin and don't get a warning. The README now recommends explicit imports.
  • The idea is to remove them in the next major version.

Comment thread web.py Resolved
Comment thread helpers.py Resolved
Comment thread helpers.py Resolved
Comment thread helpers.py Resolved
Niels V added 10 commits November 19, 2026 09:46
previously an invalid configuration for log level would cause an unclear
error, we raise a clear error that cannot be ignored. An empty or unset
log level now defaults to info.
BaseHTTPException is no longer added as a builtin, services import it
from helpers. Using helpers or sparql_escape without an import still
works for backwards compatibility, but logs a deprecation warning once
per helper. PRINT_DEPRECATION_WARNINGS (default true) disables these
warnings, similar to the ruby template.

The before_first_request warning now uses the same mechanism: Python
hides a DeprecationWarning raised outside of __main__, so it was never
shown.

The README recommends explicit imports.
it had not been working for a long time (likely since beta.1)
this is a configuration error of the service, not a client error, so a
403 was misleading. A plain exception also works outside of a request
context and matches the javascript template.
the validators returned None on success, so callers had to check the
result before returning it. They now raise a BaseHTTPException, similar
to the ruby template where they halt the request. Services returning
the result keep working, as the error response is the same.

A missing type in validate_resource_type now results in a 409 instead
of a KeyError.
aligns with sparqlEscapeDecimal in the javascript template. Values are
written in fixed-point notation, as xsd:decimal does not allow an
exponent.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants