Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / framework_spec.py: 78%

259 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Resolve inline codegen declarations from structure, not family render specs. 

16 

17This module replaces per-family ``render_spec.py`` files. Every fact a 

18generated artifact needs is derived from the family's *existing runtime 

19providers* plus the frozen plan, never from a family-name dispatch table: 

20 

21* a YAML ``replace_module._target_`` names the family's own 

22 ``@module_replacement`` factory; inspecting that factory's source reveals 

23 which generic component it constructs (``RMSNorm`` / ``GroupedExperts`` / 

24 ``GroupedQueryAttention``) and, for fused attention, the kernel entry it hands over; 

25* a YAML ``replace_module._target_`` that names a generic component class 

26 directly (under ``hyper_parallel.components.``) resolves through that 

27 component's own wrap-style constructor -- the same declaration the native 

28 ``_target_replacement_factory`` builds, so no family factory is required; 

29* a CP ``inner_wrapper`` target under the ``models/<family>/adapter`` 

30 convention resolves to the framework CP attention strategy — imports 

31 and a recognizable inner forward rewrite additionally materializes an 

32 in-artifact CP dispatch subclass; 

33 

34The source class name an artifact must model (``Qwen3MoeRMSNorm``) is not 

35duplicated here either: it is read from the rule's own ``module_type``, which 

36the YAML already carries for its type check. No model-family codegen 

37declaration remains. 

38 

39Heavy resolution (importing the real generic component to render a fused 

40attention class) stays lazy: it only runs when a fused-attention target is 

41actually present, so importing this module never pulls torch / torch_npu. 

42Resolved specs are cached so repeated lookups stay cheap and stable (callers 

43may rely on object identity across calls). 

44""" 

45 

46from __future__ import annotations 

47 

48import ast 

49import importlib 

50from dataclasses import replace 

51from functools import lru_cache 

52import inspect 

53import textwrap 

54from typing import Any, Callable, cast 

55 

56from hyper_parallel.components.modules.family import get_module_family 

57 

58from hyper_parallel.codegen.inline.component_source import render_component_source 

59from hyper_parallel.codegen.inline.ir import ( 

60 ImportPatch, 

61 ModuleSnippetPatch, 

62 ReplacementSpec, 

63 SourceObservation, 

64 StrategySpec, 

65) 

66from hyper_parallel.codegen.inline.recognition import ( 

67 ReplacementArgument, 

68 ReplacementTarget, 

69 adapter_path_parts, 

70 class_name_of, 

71 family_from_target, 

72 inner_wrapper_target, 

73 replacement_target, 

74) 

75 

76_CP_DISPATCH_SHELL = '''if self.cp_enable: 

77 return {helper_name}(self, __hp_forward_args__) 

78 

79return self._forward_impl(__hp_forward_args__) 

80''' 

81 

82 

83def cp_dispatch_shell_body(helper_name: str) -> str: 

84 """Render CP dispatch around the extracted original forward. 

85 

86 Args: 

87 helper_name: Generated helper that implements the selected CP forward. 

88 """ 

89 return _CP_DISPATCH_SHELL.format(helper_name=helper_name) 

90 

91#: The framework CP attention strategy kind (structure-keyed, not family-named). 

92CP_ATTENTION_KIND = "cp_attention" 

93 

94def _family_provider(model_type: str | None, provider: str) -> Any | None: 

95 """Return one family adapter provider module, or ``None`` if unregistered.""" 

96 if not model_type: 

97 return None 

98 from hyper_parallel.models.registry import get_model_adapter # pylint: disable=C0415 

99 

100 adapter = get_model_adapter(model_type) 

101 loader = getattr(adapter, provider, None) if adapter is not None else None 

102 if loader is None: 

103 return None 

104 return loader() 

105 

106 

107def _family_key(model_type: str | None, target: str | None) -> str | None: 

108 """Canonical family key for one lookup. 

109 

110 Every spelling of an identity (``qwen3_moe`` / ``Qwen3MoeForCausalLM``) 

111 normalizes to the registered ``model_type``, so repeated lookups share one 

112 resolved spec -- callers may rely on object identity. A target under the 

113 ``models/<family>/adapter`` convention supplies the family when the caller 

114 did not name one. An unregistered identity is kept verbatim so resolution 

115 still fails closed (``None``) instead of falling back to another family. 

116 """ 

117 if model_type is None: 

118 model_type = family_from_target(target) 

119 if not model_type: 

120 return None 

121 from hyper_parallel.models.registry import get_model_adapter # pylint: disable=C0415 

122 

123 adapter = get_model_adapter(model_type) 

124 return adapter.model_type if adapter is not None else model_type 

125 

126 

127def _factory_function(target: str, model_type: str | None): 

128 """Resolve the recorded native factory without re-executing its provider.""" 

129 del model_type 

130 module_name, _, name = target.replace(":", ".", 1).rpartition(".") 

131 if not module_name or not name: 

132 return None 

133 try: 

134 factory = getattr(importlib.import_module(module_name), name, None) 

135 except ImportError: 

136 return None 

137 return factory if getattr(factory, "_hp_module_replacement", False) else None 

138 

139 

140#: Generic components are valid direct targets without a decorator. Model-owned 

141#: classes are accepted only when their native replacement decorator marks them. 

142_COMPONENTS_PREFIX = "hyper_parallel.components." 

143 

144 

145def _direct_component_class(target: str) -> type | None: 

146 """Import a generic or natively decorated replacement class.""" 

147 module_name, _, attr = target.rpartition(".") 

148 if not module_name or not attr: 

149 return None 

150 try: 

151 module = importlib.import_module(module_name) 

152 except ImportError: 

153 return None 

154 component = getattr(module, attr, None) 

155 if not isinstance(component, type): 

156 return None 

157 if ( 

158 target.startswith(_COMPONENTS_PREFIX) 

159 or getattr(component, "_hp_module_replacement", False) 

160 ): 

161 return component 

162 return None 

163 

164 

165def _component_replacement_target(component: type) -> ReplacementTarget | None: 

166 """Read a wrap-style component's own constructor as its replacement target. 

167 

168 The structural mirror of ``_target_replacement_factory``: a component 

169 whose constructor accepts the wrapped ``module`` declares the same 

170 replacement a family factory does -- the matched source instance is 

171 handed over (``wraps_source``), and each remaining framework keyword the 

172 native factory passes (``module_fqn`` / ``context``) applies the 

173 component's own constructor default. 

174 """ 

175 parameters = inspect.signature(component).parameters 

176 if "module" not in parameters: 

177 return None 

178 arguments = tuple( 

179 ReplacementArgument(name, value) 

180 for name, value in (("module_fqn", "''"), ("context", "{}")) 

181 if name in parameters 

182 ) 

183 return ReplacementTarget( 

184 component=component.__name__, 

185 module=component.__module__, 

186 wraps_source=True, 

187 arguments=arguments, 

188 ) 

189 

190 

191def _replacement_component(target: ReplacementTarget) -> Callable[..., Any]: 

192 """Import the component class or registered family a factory constructs. 

193 

194 Lazy by construction: the component's own module is imported only when a 

195 rule that constructs it is actually present (``components.modules`` 

196 re-exports lazily, so this pulls in one submodule, never the whole set). 

197 """ 

198 module = importlib.import_module(target.module) 

199 component = getattr(module, target.component, None) 

200 if not isinstance(component, type) and get_module_family(component) is None: 

201 raise RuntimeError( 

202 f"codegen: {target.module!r} does not export the component " 

203 f"{target.component!r} the replacement factory constructs" 

204 ) 

205 return component 

206 

207 

208def _render_arguments( 

209 target: ReplacementTarget, component: Callable[..., Any] 

210) -> tuple[str, ...] | None: 

211 """Render the constructor keywords the generated call passes. 

212 

213 Arguments the factory binds to its own parameters have no value at 

214 generation time, so the component's own constructor default is emitted -- 

215 the framework never restates a component's keyword shape. ``None`` means the 

216 component does not accept one of the keywords the factory passes, i.e. the 

217 factory constructs an interface codegen cannot sink. 

218 """ 

219 parameters = inspect.signature(component).parameters 

220 rendered: list[str] = [] 

221 for argument in target.arguments: 

222 if argument.value is not None: 

223 rendered.append(f"{argument.name}={argument.value}") 

224 continue 

225 if argument.name not in parameters: 

226 return None 

227 rendered.append(f"{argument.name}={parameters[argument.name].default!r}") 

228 return tuple(rendered) 

229 

230 

231def _interface_function(factory: Any, target: ReplacementTarget) -> Any: 

232 """The family kernel entry the factory hands its component.""" 

233 interface = getattr(factory, "__globals__", {}).get(target.interface) 

234 if not callable(interface): 

235 raise RuntimeError( 

236 f"codegen: replacement factory {getattr(factory, '__name__', factory)!r} " 

237 f"hands over {target.interface!r}, which its module does not define" 

238 ) 

239 return interface 

240 

241 

242def _build_replacement_spec( 

243 factory: Any, 

244 target: ReplacementTarget, 

245 old_ctor: str, 

246 model_type: str | None, 

247) -> ReplacementSpec | None: 

248 """Build the source-level replacement one factory declares. 

249 

250 Every field comes from the factory's own structure: the class it constructs 

251 (and the module it imports it from), whether it hands the matched module over 

252 as a wrap, the constructor keywords it passes, and the family interface it 

253 hands to the component -- which is what makes the component's class rendered 

254 (visible in the artifact) instead of merely imported. ``None`` means the 

255 construction is not one codegen can sink into the generated ``__init__``. 

256 """ 

257 component = _replacement_component(target) 

258 keyword_args = _render_arguments(target, component) 

259 if keyword_args is None: 

260 return None 

261 if get_module_family(component) is not None: 

262 # A thin source-model adapter may delegate to a registered family. 

263 # Preserve that request so later TP/CP promotion does not freeze the local class. 

264 return ReplacementSpec( 

265 old_ctor=old_ctor, new_ctor=target.component, 

266 imports=(ImportPatch(target.module, (target.component,)),), 

267 mode="wrap_source", keyword_args=keyword_args, remove_class=False, defer_to_fqns=True, 

268 ) 

269 # A component that receives a family interface is rendered into the artifact, 

270 # so its class is defined there -- importing it as well would be dead weight 

271 # the rendered definition shadows. 

272 imports: list[ImportPatch] = ( 

273 [] if target.interface else [ImportPatch(target.module, (target.component,))] 

274 ) 

275 snippets: tuple[ModuleSnippetPatch, ...] = () 

276 if target.interface: 

277 provider = _family_provider(model_type, "codegen") 

278 renderer = getattr(provider, "render_replacement_source", None) 

279 if not callable(renderer): 

280 return None 

281 render_source = cast(Callable[..., Any], renderer) 

282 expanded = render_source( # pylint: disable=not-callable 

283 component, interface=_interface_function(factory, target) 

284 ) 

285 imports.extend( 

286 ImportPatch(module="", names=(), raw=line) for line in expanded.imports 

287 ) 

288 snippets = (ModuleSnippetPatch(expanded.source),) 

289 mode = "wrap_source" if target.wraps_source else "name" 

290 return ReplacementSpec( 

291 old_ctor=old_ctor, 

292 new_ctor=target.component, 

293 mode=mode, 

294 keyword_args=keyword_args, 

295 imports=tuple(imports), 

296 remove_class=not target.wraps_source, 

297 snippets=snippets, 

298 replacement_note=( 

299 f"{target.component} wraps {old_ctor}; the original class is kept " 

300 "as the wrapper input." 

301 if target.wraps_source 

302 else f"{target.component} replaces {old_ctor}." 

303 ), 

304 ) 

305 

306 

307#: Resolved-spec caches. Keyed by everything the resolution reads, so a 

308#: repeated lookup returns the same object (callers may compare identity) and 

309#: the expensive fused-attention render runs once. 

310_REPLACEMENT_CACHE: dict[tuple[str | None, Any, str | None], ReplacementSpec | None] = {} 

311_STRATEGY_CACHE: dict[tuple[str | None, str | None, bool, tuple[str, ...]], StrategySpec | None] = {} 

312 

313 

314def replacement_spec_for( 

315 target: str | None, 

316 model_type: str | None = None, 

317 *, 

318 module_type: str | None = None, 

319) -> ReplacementSpec | None: 

320 """Resolve a ``replace_module`` target to its structural component spec. 

321 

322 ``module_type`` is the matched source module's dotted type path from the 

323 YAML rule; the source class name (``old_ctor``) is its class name — a 

324 property of the matched source module, never a hand-written literal. 

325 

326 Args: 

327 target: Import path of the replacement factory or component. 

328 model_type: Optional source model type. 

329 module_type: Observed source module type used to match construction sites. 

330 """ 

331 if target is None: 

332 return None 

333 # Builder observations serialize callables as module:attribute, while YAML 

334 # commonly uses module.attribute. Both identify the same replacement. 

335 target = target.replace(":", ".", 1) 

336 family_spec = _module_family_replacement_spec(target, module_type) 

337 if family_spec is not None: 

338 return family_spec 

339 if _direct_component_class(target) is not None: 

340 return _component_replacement_spec(target, model_type, module_type=module_type) 

341 if not adapter_path_parts(target): 

342 return None 

343 model_type = _family_key(model_type, target) 

344 factory = _factory_function(target, model_type) 

345 if factory is None: 

346 return None 

347 # The spec is derived from the *factory's* structure, so the factory is 

348 # part of the key: a target re-pointed at a different factory (or a family 

349 # re-registered with one) must not reuse the previous resolution. 

350 key = (model_type, factory, module_type) 

351 if key in _REPLACEMENT_CACHE: 

352 return _REPLACEMENT_CACHE[key] 

353 spec = _resolve_replacement_spec(factory, model_type, module_type, target) 

354 _REPLACEMENT_CACHE[key] = spec 

355 return spec 

356 

357 

358 

359def _module_family_replacement_spec(target: str, module_type: str | None) -> ReplacementSpec | None: 

360 """Retain registered module-family construction instead of freezing its concrete class.""" 

361 module_name, _, name = target.replace(":", ".", 1).rpartition(".") 

362 if not module_name or not name: 

363 return None 

364 try: 

365 factory = getattr(importlib.import_module(module_name), name, None) 

366 except ImportError: 

367 return None 

368 if get_module_family(factory) is None or not class_name_of(module_type): 

369 return None 

370 return ReplacementSpec( 

371 old_ctor=class_name_of(module_type), new_ctor=name, 

372 imports=(ImportPatch(module_name, (name,)),), mode="wrap_source", 

373 keyword_args=("module_fqn=''",), remove_class=False, defer_to_fqns=True, 

374 ) 

375 

376 

377def _resolve_replacement_spec( 

378 factory: Any, model_type: str | None, module_type: str | None, target: str 

379) -> ReplacementSpec | None: 

380 """One construction path for every replacement: read the factory. 

381 

382 Whatever component a family's factory constructs, the spec is derived from 

383 that factory's own source, so a new family (or a new component inside one) 

384 needs no codegen declaration. A factory with no constructor call to sink -- 

385 or a rule with no ``module_type`` naming the source class it replaces -- has 

386 no spec, and the rule is left to the native path. 

387 """ 

388 del target 

389 # The source class the constructor call replaces: without the rule's 

390 # ``module_type`` there is no call site to rewrite, and guessing one would 

391 # silently target the wrong class. 

392 old_ctor = class_name_of(module_type) 

393 if not old_ctor: 

394 return None 

395 replacement = replacement_target(factory) 

396 if replacement is None: 

397 return None 

398 return _build_replacement_spec(factory, replacement, old_ctor, model_type) 

399 

400 

401def _component_replacement_spec( 

402 target: str, model_type: str | None, *, module_type: str | None 

403) -> ReplacementSpec | None: 

404 """Resolve a target that names a generic component class directly. 

405 

406 The component's own constructor is the declaration: the spec is derived 

407 from it exactly as the factory channel derives one from the factory's 

408 construction call, so a wrap-style component needs no family factory to 

409 be sunk into the generated ``__init__``. 

410 """ 

411 component = _direct_component_class(target) 

412 if component is None: 

413 return None 

414 key = (model_type, component, module_type) 

415 if key in _REPLACEMENT_CACHE: 

416 return _REPLACEMENT_CACHE[key] 

417 spec = None 

418 old_ctor = class_name_of(module_type) 

419 if old_ctor: 

420 replacement = _component_replacement_target(component) 

421 if replacement is not None: 

422 # No interface: a direct component hands over no family kernel, 

423 # so the factory argument of _build_replacement_spec is unused. 

424 spec = _build_replacement_spec(None, replacement, old_ctor, model_type) 

425 _REPLACEMENT_CACHE[key] = spec 

426 return spec 

427 

428 

429def strategy_spec_for( 

430 target: str | None, 

431 model_type: str | None = None, 

432 *, 

433 inner_wrapper: bool = False, 

434 construction_kwargs: tuple[str, ...] = (), 

435) -> StrategySpec | None: 

436 """Resolve a strategy target from structure. 

437 

438 A CP ``inner_wrapper`` target under the adapter convention resolves to the 

439 framework CP attention strategy (imports only). EP mutations come from the 

440 builder recorder instead of secondary structural inference. Anything else 

441 is unresolvable and yields ``None`` — recognition never guesses a strategy. 

442 

443 Args: 

444 target: Import path of the selected strategy. 

445 model_type: Optional source model type. 

446 inner_wrapper: Whether the strategy wraps the existing forward boundary. 

447 construction_kwargs: Literal arguments already recorded for the selected wrapper. 

448 """ 

449 if target is None: 

450 return None 

451 model_type = _family_key(model_type, target) 

452 key = (target, model_type, inner_wrapper, construction_kwargs) 

453 if key in _STRATEGY_CACHE: 

454 return _STRATEGY_CACHE[key] 

455 spec = _resolve_strategy_spec(target, inner_wrapper, construction_kwargs) 

456 _STRATEGY_CACHE[key] = spec 

457 return spec 

458 

459 

460def _resolve_strategy_spec( 

461 target: str, inner_wrapper: bool, construction_kwargs: tuple[str, ...], 

462) -> StrategySpec | None: 

463 if inner_wrapper: 

464 return _cp_strategy_spec(target, construction_kwargs=construction_kwargs) 

465 return None 

466 

467 

468def _cp_strategy_spec(target: str, *, construction_kwargs: tuple[str, ...] = ()) -> StrategySpec: 

469 """Build the CP strategy spec: an in-place dispatch shell plus imports. 

470 

471 A recognizable inner forward rewrite participates in inline CP: the 

472 materialization pass derives an 

473 in-artifact rewrite of the attention host whose forward falls back to 

474 ``_forward_impl`` when CP is disabled and delegates to the helper when 

475 active. The helper is the same kernel the runtime CP wrapper delegates 

476 to (trainer and codegen share one CP implementation), and the import is 

477 derived from the wrapper factory source, so this module never hardcodes a 

478 family helper and stays free of torch imports at resolution time. 

479 

480 Unrecognized wrappers carry no source body; artifact verification must 

481 reject a declared patch that was not materialized. 

482 """ 

483 resolved = inner_wrapper_target(target, construction_kwargs=construction_kwargs) 

484 if resolved is None: 

485 return StrategySpec(kind=CP_ATTENTION_KIND, imports=()) 

486 imports = tuple(ImportPatch(module, (name,)) for module, name in resolved.extra_imports) 

487 if resolved.helper_module and resolved.helper_name: 

488 imports = (ImportPatch(resolved.helper_module, (resolved.helper_name,)), *imports) 

489 if resolved.inline_body is not None: 

490 return StrategySpec( 

491 kind=CP_ATTENTION_KIND, 

492 subclass_shell=resolved.inline_body, 

493 imports=imports, 

494 definition=resolved.definition, 

495 snippets=tuple(ModuleSnippetPatch(source) for source in resolved.bindings), 

496 ) 

497 return StrategySpec( 

498 kind=CP_ATTENTION_KIND, 

499 subclass_shell=cp_dispatch_shell_body(resolved.helper_name), 

500 imports=imports, 

501 ) 

502 

503 

504__all__ = [ 

505 "CP_ATTENTION_KIND", 

506 "cp_dispatch_shell_body", 

507 "replacement_spec_for", 

508 "strategy_spec_for", 

509] 

510 

511 

512def replacement_spec_for_observation( 

513 rule: SourceObservation, model_type: str | None = None, 

514) -> ReplacementSpec | None: 

515 """Resolve the same native observation for coverage checks and rendering.""" 

516 if rule.construction is not None: 

517 return observed_constructor_spec(rule) 

518 spec = replacement_spec_for(rule.replace_target, model_type, module_type=rule.module_type) 

519 if spec is None: 

520 return None 

521 arguments = {item.split("=", 1)[0]: item for item in spec.keyword_args} 

522 arguments.update({item.split("=", 1)[0]: item for item in rule.construction_kwargs}) 

523 return replace(spec, keyword_args=tuple(arguments.values())) 

524 

525 

526def observed_constructor_spec(rule: Any) -> ReplacementSpec | None: 

527 """Use the native-selected class and its existing construction contracts.""" 

528 module_name, name = rule.construction["implementation"].replace(":", ".", 1).rsplit(".", 1) 

529 component = getattr(importlib.import_module(module_name), name) 

530 parameters = inspect.signature(component.__init__).parameters 

531 values = dict(item.split("=", 1) for item in rule.construction_kwargs) 

532 values.update({name: repr(value) for name, value in rule.construction.get("arguments", {}).items()}) 

533 arguments = [] 

534 ignored = _ignored_constructor_parameters(component) 

535 for key, value in values.items(): 

536 if key in parameters and key not in ignored and key != "module_fqn" and value != "None": 

537 arguments.append(f"{key}={value}") 

538 mode = _observed_constructor_mode(component, parameters) 

539 if mode == "wrap_source" and "module" not in parameters: 

540 return (replacement_spec_for(rule.replace_target, module_type=rule.module_type) 

541 or _observed_factory_spec(rule, component)) 

542 imports, snippets = _observed_component_source(component) 

543 return ReplacementSpec( 

544 old_ctor=class_name_of(rule.module_type), new_ctor=name, 

545 imports=imports, mode=mode, 

546 keyword_args=tuple(arguments), remove_class=False, snippets=snippets, 

547 ) 

548 

549 

550def _observed_factory_spec(rule: SourceObservation, component: type) -> ReplacementSpec | None: 

551 """Keep a proven native classmethod construction instead of guessing an initializer.""" 

552 factory = _factory_function(rule.replace_target, None) if rule.replace_target else None 

553 if not inspect.isfunction(factory): 

554 return None 

555 tree = ast.parse(textwrap.dedent(inspect.getsource(factory))) 

556 returns = [node.value for node in ast.walk(tree) if isinstance(node, ast.Return)] 

557 if len(returns) != 1 or not isinstance(returns[0], ast.Call): 

558 return None 

559 callee = returns[0].func 

560 if (not isinstance(callee, ast.Attribute) or not isinstance(callee.value, ast.Name) 

561 or factory.__globals__.get(callee.value.id) is not component): 

562 return None 

563 # No live build context is retained in a snapshot. An unused protocol 

564 # argument can be supplied, but a context-dependent factory stays unsupported. 

565 if any(isinstance(node, ast.Name) and node.id == "context" and isinstance(node.ctx, ast.Load) 

566 for node in ast.walk(tree)): 

567 return None 

568 return ReplacementSpec( 

569 old_ctor=class_name_of(rule.module_type), new_ctor=factory.__name__, mode="wrap_source", 

570 imports=(ImportPatch(factory.__module__, (factory.__name__,)),), 

571 keyword_args=("module_fqn=''", "context={}", *rule.construction_kwargs), 

572 remove_class=False, defer_to_fqns=True, 

573 ) 

574 

575 

576def _observed_constructor_mode(component: type, parameters: Any) -> str: 

577 """Require the source argument before considering a member's direct construction interface.""" 

578 module = parameters.get("module") 

579 if module is not None and module.default is inspect.Parameter.empty: 

580 return "wrap_source" 

581 if {"hidden_size", "eps"} <= parameters.keys(): 

582 return "construct" 

583 if ("config" in parameters and callable(getattr(component, "_initialize_source", None)) 

584 and callable(getattr(component, "_initialize_config", None))): 

585 return "config" 

586 return "wrap_source" 

587 

588 

589def _observed_component_source(component: type) -> tuple[tuple[ImportPatch, ...], tuple[ModuleSnippetPatch, ...]]: 

590 """Expose native member stages absent from the legacy injection records.""" 

591 if not callable(getattr(component, "parallel_module_spec", None)): 

592 return (ImportPatch(component.__module__, (component.__name__,)),), () 

593 expanded = render_component_source(component) 

594 imports = tuple(ImportPatch(module="", names=(), raw=line) for line in expanded.imports) 

595 snippets = tuple(ModuleSnippetPatch(ast.unparse(node)) for node in ast.parse(expanded.source).body) 

596 return imports, snippets 

597 

598 

599@lru_cache(maxsize=None) 

600def _ignored_constructor_parameters(component: type) -> frozenset[str]: 

601 """Read unused native arguments, following only explicit super keyword forwarding.""" 

602 owner = next(base for base in component.__mro__ if "__init__" in base.__dict__) 

603 try: 

604 tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__init__))) 

605 except (OSError, TypeError): 

606 return frozenset() 

607 inherited = _ignored_constructor_parameters(owner.__mro__[1]) if len(owner.__mro__) > 1 else frozenset() 

608 _discard_unused_super_keywords(tree, inherited) 

609 loaded = {node.id for node in ast.walk(tree) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)} 

610 return frozenset(inspect.signature(owner.__init__).parameters) - loaded - {"self"} 

611 

612 

613def _discard_unused_super_keywords(tree: ast.AST, inherited: frozenset[str]) -> None: 

614 """Exclude forwarding reads only when the native parent ignores the argument.""" 

615 for call in (node for node in ast.walk(tree) if isinstance(node, ast.Call)): 

616 if (isinstance(call.func, ast.Attribute) and call.func.attr == "__init__" 

617 and isinstance(call.func.value, ast.Call) and isinstance(call.func.value.func, ast.Name) 

618 and call.func.value.func.id == "super"): 

619 call.keywords = [kw for kw in call.keywords 

620 if not (kw.arg in inherited and isinstance(kw.value, ast.Name))]