Skip to content

feat: log deprecations once per process - #728

Merged
uniqueg merged 4 commits into
devfrom
feat/deprecation-log
Nov 6, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/deprecation-log

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

As decided by the maintainer, FOCA logs each deprecation once per process at WARNING, besides the Python warning, so that operators see deprecated uses under Gunicorn, where Python hides DeprecationWarning.

  • New module foca.deprecation. Its public API is warn_deprecated(message, stacklevel=2) and LOGGER_NAME ("foca.deprecation").
    • It emits the DeprecationWarning on every call, with the same stack level as before.
    • The first call with a message in a process also logs the message at WARNING. The record is logged before the warning is emitted, so it is logged also under -W error::DeprecationWarning.
    • It is thread-safe, and a failing log filter or handler never fails the call; the deprecation is then logged on a later call.
    • Forked processes, e.g., Gunicorn workers (also with preload_app), log again. The state is reset with os.register_at_fork, which replaces the lock rather than taking it.
  • FOCA's deprecations use it:
    • reading, setting and deleting app.config.foca;
    • get_app_config();
    • Unauthorized(www_authenticate=...) / .www_authenticate;
    • x-body-name: permission.
  • Out of scope: the warning that FOCA already logs, once per class, for exception maps with raw Werkzeug classes.

Docs:

  • docs/configuration/log.md: new section "Deprecations". It shows an example record, says how to silence the logger and that the warnings are unchanged.
  • docs/migration-0.22.md: new section "Deprecations in the logs".
  • docs/reference.md: adds foca.deprecation.

Closes #727

Verification

  • coverage run -m pytest with a private MongoDB 7.0 (--nounixsocket, port 12345), at 093c19b: 4807 passed, 2 skipped, 100% coverage.
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep scan --config .semgrep --error and mkdocs build --strict: pass. pre-commit can't fetch its hook repos through the sandbox proxy, so I ran the tools directly.
  • New tests (tests/test_deprecation.py):
    • a warning on every call, at the exact line of the caller, also through a helper with stacklevel=3;
    • one log record per message, also across 8 threads;
    • logging again, exactly once, in a forked child;
    • logging again on a later call after logging failed;
    • logging before the warning is raised when warnings are errors;
    • a failing log filter;
    • one log record from each of FOCA's three deprecation modules.
      The per-process state is reset for every test (tests/conftest.py).
  • Downstream, at 8f296fe (the later commits only add the fork reset and tests), with this branch installed over their locked environments, as in their CI (-W ignore::DeprecationWarning):
    • proTES dev (d237a18): 1615 passed, 11 skipped, 100% coverage.
    • cloud-registry dev (31c7b8f): 2338 passed, 11 skipped, 100% coverage.
    • Neither uses caplog. Apps that read app.config.foca (e.g., proTES's Gunicorn config) now log one WARNING line per process.
  • CI: all checks passed on 853ef38 and on 093c19b (CI passed). Sourcery: 4 threads; two fixed in 093c19b (log again after a failed log; the fork test now logs in the child), two answered (blocking handlers are the app's choice of handlers; custom config classes don't warn by design, refactor(config): deprecate config.foca accessors #716); all resolved.

Declined review findings

  • Test the logged-before-raised order for each site: covered once for the helper, which all sites use.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 6, 2026 18:19
`foca.deprecation.warn_deprecated()` emits the `DeprecationWarning` as
before and, the first time a message fires in a process, logs it at
WARNING on the logger `foca.deprecation`, so operators see deprecated
uses under Gunicorn, where Python hides the warnings. Thread-safe;
logging never fails the call. FOCA's deprecations (config accessors,
`www_authenticate`, `x-body-name: permission`) use it. Documented in
the logging configuration, the migration guide and the API reference.

Closes #727

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Forget the logged deprecations after `fork()`, so that each Gunicorn
worker logs them, also with `preload_app`, replacing the lock rather
than taking it. Reset the state for every test in `conftest.py`; test
the exact line of the warning, also via helpers (`stacklevel=3`), a
failing log filter, and the log records of FOCA's deprecations. Clarify
`stacklevel`, the public API, constant messages and how to silence the
logger in the docs.

Refs #727

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ignore Python's warning about forking multi-threaded processes, as the
other fork tests do; always exit the child; rename the record helper,
which shared its name with the module state.

Refs #727

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 6, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the public deprecation API and logger name that callers use to emit warnings and process-deduplicated log records.

  • foca/deprecation.py L1-73

Uses of the API

Route FOCA’s deprecated configuration accessors, error API, and permissions request-body behavior through the new deprecation API.

  • foca/config/access.py L5-173 (10 small edits)
  • foca/errors/classes.py L9-203 (6 small edits)
  • foca/security/access_control/access_control_server.py L8-140 (4 small edits)

Documentation

Document the deprecation logger’s behavior and suppression, explain its migration impact, and add the module to the API reference.

  • docs/configuration/log.md L122-145
  • docs/migration-0.22.md L172-180
  • docs/reference.md L303-304

Tests

Reset deprecation state around each test and verify warning stack levels, per-process and fork behavior, logging failures, and adoption by FOCA deprecation sites.

  • tests/conftest.py L12, L78-85
  • tests/test_deprecation.py L1-235

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8411ca2) to head (093c19b).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #728   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           71        72    +1     
  Lines         9141      9166   +25     
=========================================
+ Hits          9141      9166   +25     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 6, 2026 18:00

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/deprecation.py" line_range="69" />
<code_context>
+    if first:
+        # A faulty filter or handler of the app must not fail the call
+        with contextlib.suppress(Exception):
+            _logger.warning(message)
+    warnings.warn(message, DeprecationWarning, stacklevel=stacklevel + 1)
</code_context>
<issue_to_address>
**Slow handlers stall deprecated calls**

When a configured handler blocks indefinitely or takes an unusually long time to return, `_logger.warning()` invokes handlers synchronously with no timeout, so a stalled logging handler blocks the first call to each deprecated API using that message; request handling or startup can hang until the handler returns.

Ensure the deprecation logging path cannot block callers indefinitely, for example by using a bounded, non-blocking logging handler.
</issue_to_address>

### Comment 2
<location path="foca/deprecation.py" line_range="65" />
<code_context>
+    """
+    with _lock:
+        first = message not in _logged
+        _logged.add(message)
+    if first:
+        # A faulty filter or handler of the app must not fail the call
</code_context>
<issue_to_address>
**Recovered logging never reports deprecation**

When a filter or handler raises on the first attempt and later recovers, `_logged.add(message)` runs before `_logger.warning(message)`, and `contextlib.suppress(Exception)` hides the logging error. Later calls skip logging, so operators never see that deprecation in the process logs.

Only mark the message as logged after `_logger.warning(message)` succeeds, or remove it from `_logged` when logging raises.
</issue_to_address>

### Comment 3
<location path="foca/config/access.py" line_range="48" />
<code_context>
         except KeyError:
             raise AttributeError(_ATTRIBUTE) from None
-        warnings.warn(
+        warn_deprecated(
             "'app.config.foca' is deprecated; use 'foca.get_config()' or "
             "'foca.get_custom_config()'.",
</code_context>
<issue_to_address>
**Custom config access stays unlogged**

When an app uses a custom Flask config class, the deprecated property handlers are never installed for apps whose `app.config` uses a custom class, so reading, setting, or deleting `app.config.foca` bypasses `warn_deprecated()` and produces no deprecation log for operators.

Either ensure the deprecated attribute is intercepted for custom config classes or qualify the documented coverage to exclude them.

Also at `foca/config/access.py:62`, `foca/config/access.py:76`.
</issue_to_address>

### Comment 4
<location path="tests/test_deprecation.py" line_range="123" />
<code_context>
+        pid = os.fork()
+        if pid == 0:  # pragma: no cover (child; reports via the pipe)
+            try:
+                os.write(write, b"1" if MESSAGE in deprecation._logged else b"0")
+            finally:
+                os._exit(0)
</code_context>
<issue_to_address>
**Forked logging goes unverified**

When the fork callback clears `_logged`, but child calls to `warn_deprecated()` no longer log, in `test_logs_again_after_fork`, line 123 only reports whether `_logged` was cleared and never calls `_caller()` in the child, so the test passes even if a forked worker never emits the required log.

Call `warn_deprecated()` in the child and assert the child’s log result, for example by reporting it through the pipe.
</issue_to_address>

Linked issues

#727 feat: log deprecations once per process · 6 of 6 met

# Requirement Status Notes
1 A shared helper emits DeprecationWarning with the caller's stack level. ✅ Met foca.deprecation.warn_deprecated() emits the warning with stacklevel + 1; tests check the caller's line, including through a helper.
2 Log the first occurrence per deprecation per process at WARNING on a FOCA logger; be thread-safe and never fail the call. ✅ Met The helper tracks messages under a lock, logs first occurrences on foca.deprecation, and suppresses logging exceptions. Forked children reset the state.
3 FOCA's listed deprecations use the shared helper. ✅ Met The config accessors, get_app_config(), Unauthorized challenge argument and attribute, and permissions API body name use warn_deprecated().
4 Document once-per-process logging, the logger name, and how to silence it in the migration and logging configuration docs. ✅ Met Both docs name foca.deprecation and explain silencing it by raising the logger's level.
5 Test that a deprecation logs once per process and still emits a warning on every call; keep existing deprecation tests green. ✅ Met Tests cover one log per message, repeated warnings, concurrency, and the FOCA deprecation sites; the PR reports the existing suite passing.
6 Leave the existing warning for exception maps with raw Werkzeug classes out of scope. ✅ Met The diff does not change that warning.

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: foca/deprecation.py:69, foca/deprecation.py:65, foca/config/access.py:48, tests/test_deprecation.py:123


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/deprecation.py Resolved
Comment thread foca/deprecation.py Resolved
Comment thread foca/config/access.py Resolved
Comment thread tests/test_deprecation.py Resolved
If a filter or handler raises, forget the message, so that a later call
logs it. The fork test now calls the deprecated API in the child and
checks that it logs exactly once there (Sourcery review).

Refs #727

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit a9385c9 into dev Nov 6, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/deprecation-log branch November 6, 2026 18:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: log deprecations once per process

1 participant