sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[PORT] First-class logging module + warn_once (TS→Py)

Open strandly-the-agent opened this issue 4 months ago • 2 comments

⚠️ Filed by Strandly as part of the #2498 parity audit. Source feature verified merged + unit-tested in strands-ts. Agent-produced — this one needs a design decision, not a mechanical port (see gotchas). (No port label yet — a maintainer should add it.)

Parent: #2498

Source SDK

strands-ts

Target SDK

strands-py

Related Files

strands-ts/src/logging/index.ts
strands-ts/src/logging/logger.ts
strands-ts/src/logging/types.ts
strands-ts/src/logging/warn-once.ts
strands-ts/src/logging/__tests__/logger.test.ts
strands-ts/src/logging/__tests__/warn-once.test.ts
site/src/content/docs/user-guide/observability-evaluation/logs.mdx
site/src/content/docs/user-guide/observability-evaluation/logs.ts

What needs to be migrated

TS ships a small injectable-logger façade; Python has no logging module (uses stdlib logging.getLogger(__name__) everywhere).

  • Logger interface (types.ts:10): variadic debug/info/warn/error(...args).
  • logger (logger.ts:25): a mutable module-global singleton imported by ~43 source files.
  • configureLogging(customLogger) (logger.ts:44): swaps the global (public export).
  • defaultLogger (logger.ts:15): debug/info no-op; warn→console.warn, error→console.error.
  • warnOnce(logger, msg) (warn-once.ts:15): process-global Set<string> dedup, emit warn at most once per message. Used at 8 call sites (conversation-manager, model providers, graph, swarm, goal plugin). Not publicly exported.

Python landing points

  • warn_once is the clearly portable piece — Python has the same "unbounded execution" / "default model" nudges that would benefit (mirror the TS call sites in multiagent/, models/, conversation_manager.py). Python's conversation manager currently uses a per-instance boolean flag instead of a process-global once.
  • 81 getLogger(__name__) call sites in strands-py/, all children of the "strands" root logger (per logs.mdx). A faithful port must not disturb this hierarchy.

Gotchas / open questions (need maintainer input)

  • The injectable-global-logger pattern is a TS-ism that fights Python idiom. Python's established approach (and this SDK's) is per-module getLogger(__name__) configured by the application. Porting the global singleton verbatim would rewrite 81 call sites and abandon the standard hierarchy. Recommended defensible scope: keep getLogger(__name__), add only warn_once. Confirm before doing more.
  • warn vs warning. Stdlib is logging.Logger.warning (warn deprecated) — a Logger Protocol requiring warn wouldn't be satisfied by a stdlib logger. Use warning or an adapter.
  • Variadic args differ. TS warn(...args) concatenates (console-style); Python logger.warning(msg, *args) is printf/%-style. Don't map ...args→*args naively. warn_once(logger, msg) is single-message → ports cleanly.

Completeness of source (strands-ts)

  • Merged: ✅ · Unit tests: ✅ (logger.test.ts, warn-once.test.ts) · Integ: ❌ none.
  • Docs: ✅ for configureLogging/Logger (logs.mdx + logs.ts); ⚠️ warnOnce is undocumented / not a public export.

Confirmation

  • [x] The change is complete in the source SDK (merged + unit-tested); every related artifact is listed above.

strandly-the-agent avatar Jul 09 '26 19:07 strandly-the-agent

@strandly-the-agent can you look into how the logger behaves for Typsescript and compose a design document on how to implement in python?

jimbrub avatar Oct 07 '26 15:10 jimbrub

TL;DR — don't port the TS logging module; the design decision is already made in strands-py/AGENTS.md:78-82, and Python stdlib already gives us every behaviour the TS module adds. What's left is a small convergence PR.

  • TS behaviour (verified @ 1556ede): a mutable module-global logger (63 importers) behind a 4-method console-style Logger interface, swapped via configureLogging; default = warn/error to console, debug/info no-op. warnOnce is a process-global Set<string> keyed on the message, 16 call sites, not exported — and it already costs TS test isolation (vi.mock in 6 test files) and a duplicated copy in harness-ts/src/logging.ts.
  • Python equivalents already exist: stdlib's lastResort handler gives the same default (WARNING+ to stderr, nothing else — verified); handler injection on logging.getLogger("strands") is configureLogging; warnings.warn dedupes once per call site + message (verified, incl. pytest resetting it per test). 15 of 16 warnOnce sites are developer-facing config nudges, which is exactly the warnings.warn audience.
  • Proposed PR: convert the two Python sites that drifted — multiagent/graph.py:499 (logger.warning on every build()) and models/model.py:339-348 (logger.warning + hand-rolled _utilization_limit_warned flag) — to warnings.warn(..., stacklevel=N); one docs paragraph on warnings / captureWarnings in logs.mdx; one parity line in root AGENTS.md (warnOnce ↔ warnings.warn) so #2498 stops re-filing this.
  • Not recommended: a faithful port (103 call sites, breaks the documented "strands" logger hierarchy, warn ≠ warning) or an internal warn_once (contradicts AGENTS.md:82; no operational site needs it today).

Open question for you: agree warn_once should not exist in Python, and close this with the convergence PR? Happy to open that PR if so.

Full design doc (TS behaviour, site-by-site mapping, options, concrete change list)

Recommendation

Do not port the module. Python's stdlib already provides every behaviour the TS module adds, and strands-py/AGENTS.md:78-82 already settles the warn_once question ("if you catch yourself building a process-global warn-once set over the logger, you almost certainly want warnings.warn"). What remains is a small convergence PR: two Python call sites that drifted from that rule, one docs paragraph, and one line in the root AGENTS.md so the parity audit stops re-filing this.

1. How the TS logger behaves

Piece Where Behaviour
Logger interface strands-ts/src/logging/types.ts:10 debug/info/warn/error(...args: unknown[]) — console-style variadic, args are passed through, not formatted
logger logger.ts:25 mutable module-global (export let), imported by 63 source files
configureLogging(l) logger.ts:44 reassigns the global; the only public entry point (index.ts:312-313 exports configureLogging + Logger type)
defaultLogger logger.ts:15 debug/info no-op; warn → console.warn; error → console.error
warnOnce(logger, msg) warn-once.ts:15 process-global Set<string>, dedupe key = full message string; internal, not exported

Level usage in strands-ts/src (non-test): debug 90, info 8, warn 190, error 12.

warnOnce has 16 call sites today (the issue body's "8 incl. conversation-manager" is stale): models/anthropic.ts:159,163, models/bedrock.ts:441,634, models/google/model.ts:96, models/model.ts:392, models/openai/cache.ts:94,111, models/openai/model.ts:87, models/vercel.ts:265,277,350,389, multiagent/graph.ts:174, multiagent/swarm.ts:168, vended-plugins/goal/plugin.ts:269.

Every one of them is a developer-facing usage nudge (default modelId/maxTokens, unsupported cacheConfig/ttl/strategy, no maxSteps/timeout, contextWindowLimit unset) except bedrock.ts:634 (CountTokens AccessDeniedException → heuristic fallback), which is operational and is also guarded by SKIP_COUNT_TOKENS_MODELS, so the once-set is redundant there.

Costs the design already pays in TS — worth not importing:

  • Test isolation. The global Set leaks across tests, so 6 test files vi.mock('../../logging/warn-once.js') (e.g. models/__tests__/bedrock.test.ts:152) and assert on the mock rather than the log.
  • Message-as-key. Dropping a field=<value> from a message collapses every distinct value into one warning (seen in review on #4055).
  • Not exported, so duplicated. harness-ts/src/logging.ts carries its own copy of logger + warnOnce + a resetWarnOnce() for tests; strands-ts/src/a2a/logging.ts hand-rolls a separate _logged boolean.

2. What Python already has

  • 103 logging.getLogger(__name__) sites, all under the strands root logger (documented in site/.../logs.mdx, Python tab). Levels: debug 398, info 25, warning 183, error 21, exception 28.
  • 40 warnings.warn(...) sites, split from logger.warning by audience per strands-py/AGENTS.md:78-82 (reference impl: models/_validation.py uses stacklevel=4).
  • Default behaviour already matches TS with zero code. With no handler configured, stdlib's lastResort handler writes WARNING+ to stderr and drops DEBUG/INFO — verified on 3.13: logger.debug/info silent, logger.warning/error printed. That is defaultLogger.
  • Injection already exists. configureLogging(pino) ≡ logging.getLogger("strands").addHandler(...); structlog/loguru users attach an intercept handler. Standard Python, already in the docs.
  • Dedupe already exists for the right audience. warnings.warn under the default filter emits once per (message, category, module, lineno). Verified: a loop calling a warnings.warn(f"model_id=<{id}> …", stacklevel=2) helper 3× for a then 3× for b prints exactly two lines — same per-distinct-message semantics as warnOnce, but scoped to the user's call site (better: it tells them which line), with no global state. pytest resets the registry per test (verified: two tests both pytest.warns on the same line, both pass) — so none of the vi.mock ceremony. Operators who want these in logs anyway call logging.captureWarnings(True) → py.warnings logger.

TS warnOnce sites mapped onto Python

TS site Python today Verdict
default modelId (bedrock / anthropic / openai / gemini) models/bedrock.py:1793 warnings.warn(…, stacklevel=2) ✅ already correct
openai ttl not a retention value (cache.ts:111) models/_openai_cache.py:69 warnings.warn(…, stacklevel=4) ✅
goal plugin unbounded (goal/plugin.ts:269) vended_plugins/goal/plugin.py:272 warnings.warn(…, stacklevel=2) ✅
bedrock CountTokens AccessDenied (bedrock.ts:634) models/bedrock.py:1309 logger.warning + _SKIP_COUNT_TOKENS_MODELS (once per model) ✅ operational → logger is the right audience
graph unbounded (graph.ts:174) multiagent/graph.py:499 logger.warning(...) — fires on every build(), no dedupe, wrong audience ❌ fix
contextWindowLimit default (model.ts:392) models/model.py:339-348 logger.warning guarded by a per-instance _utilization_limit_warned flag; 4 tests poke the flag ❌ fix
unknown cache strategy (vercel.ts:277) models/anthropic.py:426 logger.warning inside request formatting — likely fires per request ⚠️ implementer to confirm, probably same fix
swarm unbounded (swarm.ts:168) Python Swarm defaults are bounded (max_handoffs=20, max_iterations=20, execution_timeout=900) n/a
anthropic default maxTokens, vercel cacheConfig Python max_tokens is Required[int]; no Vercel provider n/a

3. Options considered

A. Faithful port — Logger Protocol + configure_logging() + a module-global logger. Rejected. Rewrites 103 call sites; breaks every user who configures logging.getLogger("strands") as the docs tell them to; a stdlib Logger has warning not warn so it would not even satisfy the Protocol; TS variadic pass-through ≠ Python %s interpolation (ruff G enforces the latter). Nothing is gained — handler injection is what stdlib is.

B. Internal strands/_logging.py::warn_once(logger, msg) only. Rejected for now. Directly contradicts AGENTS.md:82; every candidate site is developer-facing, where warnings.warn already dedupes without global state. Keep in reserve only if a genuinely operational warning that repeats per request appears — none does today (the one operational case is already guarded).

C. No new module; converge the drifted sites + docs. ← recommended.

4. Proposed change (option C)

One small PR in strands-py/ (+ docs):

  1. multiagent/graph.py:499 → warnings.warn("graph has no max_node_executions or execution_timeout; execution is unbounded", stacklevel=3) (GraphBuilder._validate_graph ← build() ← user, so stacklevel=3 lands on the user's build() line; the separate Graph._validate_graph at :711 does not warn). Message text mirrors graph.ts:174 per the parity rule.
  2. models/model.py:339-348 → warnings.warn(f"context_window_limit not set on model, using default of {DEFAULT_CONTEXT_WINDOW_LIMIT} for utilization estimate | set context_window_limit in your model config for accurate results", stacklevel=2); delete the _utilization_limit_warned attribute. Note estimate_utilization is called from SDK internals (conversation managers), so stacklevel cannot reach user code — dedupe still works (per internal call site), which is the goal. Update tests/strands/models/test_model.py:675 and the three flag-resets in tests/strands/agent/test_conversation_manager.py:829, test_summarizing_conversation_manager.py:874,939 to pytest.warns(UserWarning, match=...) / warnings.catch_warnings as appropriate.
  3. models/anthropic.py:426 — if it fires per request, same treatment with the right stacklevel.
  4. Docs logs.mdx, Python tab — add a short "Usage warnings" note: config/usage nudges are emitted via Python warnings (not the logger); control with -W / PYTHONWARNINGS (e.g. -W error::UserWarning in CI); logging.captureWarnings(True) routes them into the py.warnings logger if you want them in log aggregation.
  5. Root AGENTS.md parity section — one line: TS warnOnce(logger, msg) ↔ Py warnings.warn(msg, stacklevel=N), so the #2498 audit has a recorded mapping and stops flagging this as a gap.
  6. Tests: pytest.warns(UserWarning, match="execution is unbounded") for graph; same for model default. No test for "second call does not warn" — that's stdlib behaviour, not ours.

5. Open questions for maintainers

  • Agree warn_once should not exist in Python (per AGENTS.md:82), and close #3152 with the convergence PR?
  • Should the issue be retitled from [PORT] to reflect that it's a convergence/cleanup, or closed in favour of a new one?

strandly-the-agent avatar Oct 07 '26 15:10 strandly-the-agent