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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions .github/workflows/python-logpoint-corpus.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
name: Python logpoint corpus

# The Python logpoint check (issues #1334, #1349) on both sides of the
# f-string grammar change in Python 3.12. ci.yml's build-and-test job runs the
# same corpus on its own Python (3.11); this job runs it on 3.12 and 3.13: the
# properties of the check against the interpreter itself, the pins recorded for
# its minor version (named here, so an interpreter with none fails), and the
# process-settings counterexamples, live. Pull requests that touch the check or
# what the live tests go through, and on demand; never on a push to main
# (ci.yml is the badge).

on:
pull_request:
branches: [ main ]
paths:
- 'packages/shared/src/interfaces/python-logpoint-check.ts'
- 'packages/shared/src/interfaces/adapter-policy-python.ts'
- 'packages/shared/src/interfaces/adapter-policy.ts'
- 'packages/shared/src/utils/to-source-breakpoint.ts'
- 'packages/shared/src/models/**'
- 'packages/adapter-python/src/**'
- 'src/server.ts'
- 'src/server/handlers/breakpoint-tools.ts'
- 'src/server/handlers/shared.ts'
- 'src/session/launch/debug-launcher.ts'
- 'src/session/attach/attach-controller.ts'
- 'src/session/log-message-checkers.ts'
- 'src/session/breakpoints/logpoint-checks.ts'
- 'src/session/breakpoints/breakpoint-controller.ts'
- 'src/session/launch/proxy-launcher.ts'
- 'src/session/launch/spawn-command.ts'
- 'src/session/session-manager-core.ts'
- 'src/proxy/adapter-cwd.ts'
- 'tests/adapters/python/integration/logpoint-interpreters.ts'
- 'tests/adapters/python/integration/logpoint-pins.ts'
- 'tests/adapters/python/integration/python-logpoint-*.test.ts'
- 'tests/adapters/python/integration/logpoint-corpus/**'
- 'requirements/debugpy.txt'
- 'pnpm-lock.yaml'
- '.github/workflows/python-logpoint-corpus.yml'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: python-logpoint-corpus-${{ github.ref }}
cancel-in-progress: true

jobs:
corpus:
name: Logpoint corpus (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
python-version: ['3.12', '3.13']
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Setup pnpm
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
- name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22.x'
cache: 'pnpm'
- name: Setup Python ${{ matrix.python-version }}
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python-version }}
- name: Install Python dependencies
run: |
python -m pip install --require-hashes -r requirements/pip.txt
python -m pip install --require-hashes -r requirements/debugpy.txt
python -c "import sys, debugpy; print(sys.version, debugpy.__version__)"
- name: Install dependencies
run: pnpm install --frozen-lockfile
env:
SKIP_ADAPTER_VENDOR: 'true'
- name: Build project
run: pnpm run build:ci
# Both suites skip without a Python that has debugpy; a skip here would
# mean this job proved nothing, so the report must show passes and no skips.
- name: Run the logpoint corpus, emulated and live, and the process settings
env:
MCP_LOGPOINT_PYTHONS: python
PYTHON_PATH: python
run: |
pnpm exec vitest run --project integration tests/adapters/python/integration/python-logpoint-corpus.test.ts tests/adapters/python/integration/python-logpoint-live.test.ts tests/adapters/python/integration/python-logpoint-process-settings.test.ts --reporter=default --reporter=json --outputFile=/tmp/logpoint-corpus.json
node -e "const r=require('/tmp/logpoint-corpus.json'); console.log('passed', r.numPassedTests, 'skipped', r.numPendingTests + r.numTodoTests); if (r.numPassedTests === 0 || r.numPendingTests + r.numTodoTests > 0) process.exit(1)"
1 change: 1 addition & 0 deletions changelog.d/1334.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**A Python logpoint written like an f-string, or with a literal `%` in its text, logs what it means instead of an error at every hit** — debugpy evaluates each `{...}` group of a `logMessage` as a plain Python expression inside one `%`-template, so `{entry!r}`, `{total:.2f}` and `{x=}` were accepted and then logged `invalid syntax (<string>, line 1)` (or `invalid decimal literal`) at every hit, and `100% {x}` logged `unsupported format character`. Now, when a launch starts (and for a logpoint set while the program runs), the program's own interpreter checks each message with the debugpy it runs: a message that runs is sent exactly as written; one the check finds cannot run for any values gets the smallest repair that interpreter validates — each failing group as the same field written as an f-string (`{f'{entry!r}'}`), the text's `%` doubled where the template cannot format — and the answer shows `logMessageSent` (what debugpy received) and `logMessageCheck` (why, and on which Python and debugpy); one with no such repair is sent as written and the answer says what every hit logs in its place; an assignment expression (`{step:=99}`) is named, because where it runs it assigns. Nothing is refused, `list_breakpoints` keeps the message as written in `logMessage`, and the launch, restart and attach answers list the logpoints the check had something to say about in `logMessageChecks`. Not checked, and sent as written with the reason: an attach, a launch that names its own `python`, `pythonPath` or `pythonArgs`, a child process whose interpreter cannot be confirmed as the checked one, and a check that ran out of its time (2 s from the question, 5 s when it starts the checker, so a `set_breakpoint` waits no longer). The checker relaxes the settings of its own process that the compiler is known to consult (the integer digit limit, warnings filters), and where it cannot relax one and can tell (its recursion limit, its memory, an audit hook added from Python) it answers "not checked" instead of failing the message. The Python guide lists the limits: a program that made its own compiler stricter can still fail where the check said it runs, a message with a starred group (`{*items}`) has the `%` in its text left unexamined, and an audit hook registered from C in the checker's process is not told apart from the compiler (#1334, #1349)
17 changes: 17 additions & 0 deletions docs/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@ set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15,

A logpoint never pauses: it interpolates the `{expressions}` and writes the line to `get_output` while the program keeps running. Each hit does cost time, however — measured at 24.7 µs per hit on Python 3.13 + debugpy (`sys.monitoring`, 2.5% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 58× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run and about 6,000 lines/s draining afterward), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See [Logpoints](../tool-reference.md#logpoints) for measurement conditions and what was not measured.

#### What a logpoint message may contain

A field is an expression in the program's language. For Python, f-string field syntax (`{x!r}`, `{total:.2f}`, `{x=}`) is accepted where the server checked the message on the program's own interpreter, which takes a launched session (the launches that are not checked are listed below). Elsewhere the message goes to debugpy as written, which evaluates each field as a plain expression, and the answer says it was not checked. debugpy's own reading wins wherever the check finds it can run the message: `{{x}}` is a set and `%%` is `%`.

debugpy turns the message into one Python expression — the text becomes a `%`-template and each `{...}` group a plain expression — and evaluates it at every hit. When the launch starts (and for a logpoint set while the program runs), the server asks the program's own interpreter, with the debugpy it runs, whether that expression can run; nothing is evaluated in that check, and nothing is refused:

- A message that runs is sent exactly as written. If it contains an assignment expression (`{step:=99}`, which an f-string would read as a format spec), the answer says so, because where it runs it assigns — on Python 3.13 and later to the running function's own variable, and on 3.12 too with some debugpy versions (1.8.0 does, 1.8.20 does not) — and names the f-string reading.
- A message the check finds cannot run for any values is repaired in the smallest way that the interpreter validates: each group that does not compile on its own becomes the same field as an f-string (`{x!r}` is sent as `{f'{x!r}'}`), and when the text cannot be formatted with `%` for any values (`100% {x}`), the text's `%` is doubled. Every other part is untouched. The answer shows `logMessageSent`, what debugpy received, and `logMessageCheck`, why; `list_breakpoints` keeps the message you wrote in `logMessage`. A message with a starred group (`{*items}`) is the exception for `%` (below).
- A message that cannot run and has no such repair (a brace inside a string in a field, `{d['}']}`, which debugpy splits there) is sent as written, and the answer says why and what every hit logs in its place: a compile error, a `%` formatting error or debugpy's "Unbalanced braces" line, with CPython's words where CPython has some.
- Not checked, and sent as written, with the reason in the answer: an attach (the program runs in a process this server did not start), a launch that names its own interpreter or interpreter flags (`python`, `pythonPath`, `pythonArgs`), a child process whose interpreter cannot be confirmed as the checked one, a message longer than 4,096 characters, a `%`-directive width or precision of more than 4 digits, or widths and precisions adding up to more than 65,536 (a message with a starred group is not held to these, since its `%` is not examined at all), anything the check itself could not finish (its recursion limit, its memory, the interpreter's own tokenizer raising on a field, which Python 3.12.13's does on one known shape, an audit hook added from Python in its process that raised while it compiled), and a check that ran out of time (below).

The check runs in a short-lived helper process on the program's interpreter, started for a run's first logpoint and stopped when the run ends (when the program and every child process it started have ended), on `close_debug_session` (which waits for it), and when the server exits; it reads its input until the server goes away. A check has 2 seconds from the moment it is asked, waiting behind other checks included, or 5 seconds when it starts the helper: a `set_breakpoint` is delayed by no more than that however many calls arrive at once, and past it the message is sent as written and the answer says it was not checked. A launch's checks share one such budget. When the helper cannot be started, exits before it has answered, or does not answer in its first 5 seconds, the run's later checks are answered at once as not checked, with that reason, and nothing is started again until the next run; a helper that fails after it had answered is started again once in the run.

The check is a verdict in one direction only. What it finds cannot compile is a fact about the text, meant to hold in every process: the helper is a sibling of the program on the same interpreter binary, and the settings of its own process that the compiler is known to consult are relaxed in it — the integer digit limit lifted, warnings ignored, its working directory kept off the path of the modules the compiler imports — and what it cannot relax (the recursion limit, memory, an audit hook added from Python) makes the message not checked instead of failed. One thing in its own process it does not tell from the compiler is an audit hook registered from C (below). What it finds compiles can still fail at a hit in a program that made its own compiler stricter: one that turns warnings into errors (`-W error`, `PYTHONWARNINGS=error`, `warnings.simplefilter("error")`: `{1 is 1}` then logs `"is" with 'int' literal`), one that lowered the integer digit limit (`sys.set_int_max_str_digits(640)`, `PYTHONINTMAXSTRDIGITS`: a long literal then logs `Exceeds the limit (640 digits)`), one with a lower recursion limit or a deeper stack at the hit, one with an audit hook, and a child process started with interpreter flags of its own (`-W error`, `-X int_max_str_digits=640`), which a child's check, made on the same interpreter binary, does not see. That is what "this check did not execute a hit" in the answer means. A repair claims only a compile: it was not run, and real values can still raise. A message with a starred group (`{*items}`) is checked for what compiles only, whatever the verdict: how many values the group gives is known at the hit alone, so the text's `%` is not examined and never doubled. `{*items} 100%` is answered as running and `{x!r} {*items} 100%` is sent as `{f'{x!r}'} {*items} 100%`; every hit of either logs an error in its place. A rewritten field is different source text from the one you wrote, so a program that inspects what it compiles — an audit hook that judges `compile` events by their source — can tell `{f'{x!r}'}` from `{repr(x)}` and treat them differently.

Four more things a user can meet, each with what the check does there. On macOS (and other systems without `/proc`) a child process's executable cannot be looked up, so every logpoint of an adopted child there is not checked (the root's are). The helper runs with the debug adapter's environment and working directory, not the launch's `env` or `envFile`: what a launch sets for the program alone (`PYTHONWARNINGS=error`, a `PYTHONPATH`) is not seen by the check, which answers as if it were not set, and is one more way a program can be stricter than its check. A file on the `PYTHONPATH` the helper inherits that stands in for a module the compiler uses (`unicodedata`) and leaves it without its table of character names makes every check of that run not checked; that takes an interpreter that loads the module from a file, and one that has it built in (Ubuntu 24.04's own Python 3.12 is one) never loads the file and answers as usual. An audit hook registered from C in the helper's process (an extension calling `PySys_AddAuditHook`) is not told apart from the compiler, as a hook added from Python is: a `SyntaxError` or `ValueError` it raises while the check compiles is read as the text's, and the message can then be answered as failing, or be rewritten.

### 3. Start Debugging

Start debugging your Python script:
Expand Down
12 changes: 11 additions & 1 deletion packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ export type {
LiveUpdateRequest,
ProgramEndContext,
ProgramEndExplanation,
LogMessageVerdict,
LogMessageChecker,
LogMessageCheckerSpec,
LogMessageCheckerReply,
ChildSessionStrategy,
AdapterSpecificState,
CommandHandling,
Expand Down Expand Up @@ -236,6 +240,12 @@ export {
} from './interfaces/js-launch-defaults.js';
export type { JsLaunchSkipInputs, JsLaunchSourceMapInputs, JsLaunchWorkspaceOptions } from './interfaces/js-launch-defaults.js';
export { PythonAdapterPolicy } from './interfaces/adapter-policy-python.js';
export {
PYTHON_LOGPOINT_CHECKER,
PYTHON_LOGPOINT_CHECKER_SOURCE,
checkPythonLogMessage,
verdictFromCheckerAnswer
} from './interfaces/python-logpoint-check.js';
export { RubyAdapterPolicy } from './interfaces/adapter-policy-ruby.js';
export { RustAdapterPolicy } from './interfaces/adapter-policy-rust.js';
export { CppAdapterPolicy } from './interfaces/adapter-policy-cpp.js';
Expand Down Expand Up @@ -313,7 +323,7 @@ export {
type VersionProbeOptions,
type VersionProbeResult
} from './utils/version-probe.js';
export { toSourceBreakpoint, toWireSourceBreakpoint, type BreakpointFields, toFunctionBreakpoint, type FunctionBreakpointFields } from './utils/to-source-breakpoint.js';
export { toSourceBreakpoint, toWireSourceBreakpoint, type BreakpointFields, toFunctionBreakpoint, type FunctionBreakpointFields, toInitialBreakpoint, type InitialBreakpoint } from './utils/to-source-breakpoint.js';
export {
JS_LOGPOINT_BINDING,
JS_LOGPOINT_CLEAR,
Expand Down
10 changes: 7 additions & 3 deletions packages/shared/src/interfaces/adapter-policy-js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import type { DebugProtocol } from '@vscode/debugprotocol';
import * as path from 'path';
import type { AdapterPolicy, AdapterSpecificState, CommandHandling, LocalVariableExtraction, QueuedDapCommand, StopReasonContext, PendingStopContext, StepInFilterContext, UnresolvedSourceContext, GeneratedFileCandidate, GeneratedFileContext } from './adapter-policy.js';
import type { AdapterPolicy, AdapterSpecificState, CommandHandling, LocalVariableExtraction, LogMessageVerdict, QueuedDapCommand, StopReasonContext, PendingStopContext, StepInFilterContext, UnresolvedSourceContext, GeneratedFileCandidate, GeneratedFileContext } from './adapter-policy.js';
import { generatedFileCandidatesFrom } from './adapter-policy.js';
import {
jsLaunchBlackboxesNodeModules,
Expand Down Expand Up @@ -324,8 +324,12 @@ export const JsDebugAdapterPolicy = {
condition: compiled.condition
};
},
validateLogMessage: (logMessage: string, condition?: string): string | undefined =>
validateJsLogpoint(logMessage, condition),
// A message that does not compile is refused up front (issue #853); the
// checker argument is never used: the compile is this policy's own.
validateLogMessage: (logMessage: string, condition?: string): LogMessageVerdict => {
const problem = validateJsLogpoint(logMessage, condition);
return problem === undefined ? { status: 'runs' } : { status: 'refused', reason: problem };
},
// js-debug implements no DAP setFunctionBreakpoints (upstream out of scope,
// vscode-js-debug#952), so ours are delivered out of band (issue #295): the
// proxy's CdpFunctionBreakpointBridge resolves names over the child
Expand Down
11 changes: 10 additions & 1 deletion packages/shared/src/interfaces/adapter-policy-python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
* Encodes debugpy specific behaviors and variable handling logic.
*/
import type { DebugProtocol } from '@vscode/debugprotocol';
import type { AdapterPolicy, AdapterSpecificState, CommandHandling, LocalVariableExtraction, StepInFilterContext, UnboundBreakpointContext } from './adapter-policy.js';
import type { AdapterPolicy, AdapterSpecificState, CommandHandling, LocalVariableExtraction, LogMessageChecker, LogMessageVerdict, StepInFilterContext, UnboundBreakpointContext } from './adapter-policy.js';
import { emptyLocalVariableExtraction, extractionFromScope } from './adapter-policy.js';
import { checkPythonLogMessage } from './python-logpoint-check.js';
import type { StackFrame, Variable } from '../models/index.js';
import type { DapClientBehavior, DapClientContext, ReverseRequestResult } from './dap-client-behavior.js';
import type { ChildAdoptionContract, ChildReport } from './child-adoption.js';
Expand Down Expand Up @@ -111,6 +112,14 @@ export const PythonAdapterPolicy = {
// correctly, sends no `initialized`: the worker does not wait for one (#746).
honoursNoDebug: true,
supportsLogPoints: true,
// debugpy evaluates each `{...}` group of a logMessage as a plain Python
// expression at every hit, so an f-string-style field (`{x!r}`) or a
// literal `%` in the text can log an error at every hit (issues #1334,
// #1349). The program's own interpreter checks the message; nothing is
// refused, a message that runs goes as written, and before any run there
// is no verdict: the launch checks it.
validateLogMessage: (logMessage: string, _condition?: string, checker?: LogMessageChecker): Promise<LogMessageVerdict> | undefined =>
checker ? checkPythonLogMessage(logMessage, checker) : undefined,
supportsFunctionBreakpoints: true,
supportsReverseStartDebugging: false,
// debugpy runs exactly one of these (`debugpy/adapter/clients.py`: '"program",
Expand Down
Loading
Loading