Skip to content

infrastructure: investigate a Hooks abstraction and callback exception boundary #143

Open

Description

@schlessera

Context

Follow-up to #27's maintainer ruling (2026-10-23): choose B, view-only graceful degradation for now, and keep an issue to investigate a possible Hooks abstraction. A general callback/lifecycle boundary remains deferred, not solved by the view work. The earlier proposal is recorded on #27.

At reviewed main 15cac4c2, services register callbacks directly with WordPress; src/Infrastructure/ServiceBasedPlugin.php:1220-1227 installs its registration callback and :1781-1821 (maybe_register_service()) constructs/registers a service without a general exception boundary. Principle 10 calls for debug visibility and graceful production behaviour, while principles 4 and 5 favour WordPress hooks and injected collaborators.

Current proposal and maintainer questions

The concrete proposal is posted in the comments. Do not repeat the investigation or implement its recommendations as rulings. Choices still needing approval are: direct callbacks versus explicit guards versus an injected Hooks wrapper versus declarations; legacy activation/deactivation failure policy; explicit registering/registered/failed state and container insertion timing; production reporting and whether views participate; unchanged versus wrapped debug exceptions; staging the work; and exactly which resulting boundary unblocks #35.

For a wrapper, the proposal explicitly identifies callback identity/removal differences, strict scalar-call behaviour, by-reference rejection and an optional enforcement-rule migration. Those are compatibility questions, not approved implementation details. Scoped lifecycle/uninstall failures already propagate under #34 and stay outside any proposed containment unless the maintainer explicitly revises that ruling.

The old #27 recommendation was superseded by the view-only choice; it is prior art only. #34/#36/#27 are now closed/implemented, so references to their proposed future work are historical. Preserve their actual contracts when preparing the eventual implementation issue(s).

The optional registration-history/Query Monitor implementation from #38/#163 is now present. Any eventual boundary proposal must preserve its opt-in/disabled path and actual-decision history; that implementation does not approve the proposed production diagnostic action or view participation.

Asset loading now has its own implemented boundary in src/Infrastructure/ServiceBasedPlugin.php:2071-2105 (#37/#177): debug rethrows; production skips the failed service's remaining assets for that enqueue point and continues other services. Preserve that ruled behaviour alongside the view boundary. It does not settle the general Hooks proposal.

Scope

Investigate a potential injected Hooks abstraction and the general exception boundary. Deliver a concrete proposal, not implementation. Compare it with keeping direct WordPress hook registration and with capability-based declarations. Use the existing #27 proposal as prior work rather than treating it as approved.

Out of scope

Acceptance criteria

  • Explain the benefit and cost of wrapping hooks, with sample service usage and injected collaborator wiring.
  • Address callback identity/removal and has_* interoperability, priorities/accepted arguments, zero-argument filter callbacks, and callbacks that add hooks dynamically.
  • Specify action/filter failure fallbacks, exception/debug behaviour, output-buffer/partial-output handling, and whether production diagnostic hooks are justified.
  • Explain boundary placement and failure granularity for registration, pending/delayed services, activation/deactivation and infrastructure: lifecycle interfaces for multisite and uninstall #34's implemented lifecycle edges; identify partial-registration/dependency consequences.
  • Assess compatibility, teaching cost, optional/default construction and architecture enforcement without weakening gates.
  • Post options, trade-offs, recommendation and precise remaining maintainer questions before implementation. Any approved API/behaviour change must have its own compatibility ruling.

Verification

Review the written proposal against docs/design-principles.md and the current hook APIs and architecture rules. Include an implementation verification plan covering both debug modes, action/filter fallback, callable removal and lifecycle failures. Eventual code must pass composer test and composer lint; this spike has no implementation deliverable.

Impact on generated plugins

Investigation only. No API or runtime behaviour change. Potential wrapper adoption would affect callback identity and service dependencies; quantify those migrations in the proposal.

Priority p3: explicitly deferred exploration while #27 takes the smaller view-only approach.

Updated 2026-10-23: repaired the ServiceBasedPlugin citations against 8164f4a (after #154). The design proposal is posted in the comments; the issue waits on a maintainer ruling (needs: decision).

Updated 2026-10-23: Preserved the posted Hooks/boundary proposal and folded its exact unresolved policy/compatibility questions into the body; corrected moved registration anchors and reconciled implemented #34/#36/#27. Added breaking for proposed behavioural/API migrations, without approving them.

Updated 2026-10-23: Repaired registration anchors at main 61a9b00 and reconciled implemented #38/#163. The posted boundary/wrapper questions remain unapproved; existing opt-in history and disabled-path requirements must be preserved.

Updated 2026-10-24: Repaired registration anchors and reconciled the implemented asset boundary from #177. General Hooks/lifecycle/state/reporting choices still need the posted maintainer rulings; the existing scoped-lifecycle, view and asset policies remain authoritative. Reviewed origin/main 15cac4c2.

Activity

  1. added
    type: spikeTime-boxed investigation. The deliverable is a written decision, not code.
    area: infrastructuresrc/Infrastructure: services, injector, views, autoloader. What generated plugins build on.
    priority: p3Someday. Needs a driving use case before it starts.
    agent-readyContext and acceptance criteria are complete enough for an agent to take this unattended.
    on Oct 23, 2026
  2. self-assigned this
    on Oct 23, 2026
  3. schlessera commented on Oct 23, 2026

    @schlessera
    MemberAuthor

    Picking this up. It is a spike, so the deliverable is a design proposal posted here, with no branch or implementation before a ruling (the branch would be spike/143-hooks-boundary if a prototype ever needed one).

  4. schlessera commented on Oct 23, 2026

    @schlessera
    MemberAuthor

    Design proposal: a Hooks collaborator and the exception boundary

    This is checked against origin/main at 8164f4a, which already includes #154 (delayed registration priority, #36). Every WordPress claim is checked against WordPress 6.9.4 core: wp-includes/class-wp-hook.php, wp-includes/plugin.php, wp-admin/includes/plugin.php, wp-includes/class-wp-fatal-error-handler.php and wp-includes/class-wp-recovery-mode.php. A throwaway prototype that loads core's own class-wp-hook.php and plugin.php reproduced the WP_Hook behaviour and the wrapper pitfalls below on PHP 7.4 and 8.3. Nothing was committed. An independent review of a first draft found several holes; this version fixes them.

    The body's citation ServiceBasedPlugin.php:724-740 has drifted: maybe_register_service() is now at :782-799. I have corrected it in the body.

    What is already decided

    • views: degrade gracefully on creation and rendering failures in production #27 (ruling): views only for now, shipped in Degrade view creation and rendering failures in production #150. The view factories rethrow the original exception in debug mode and return an EmptyView in production (src/Infrastructure/View/SimpleViewFactory.php:66-78, TemplatedViewFactory.php:97-108). A failing template throws FailedToLoadView in debug mode and renders '' in production (SimpleView.php:135-154). That ruling approved none of the following, so they are all open here: a general callback wrapper, a capability-based hook API, a production diagnostic action, a debug-mode wrapper exception, a change to when services enter the container, and a per-service catch policy.
    • infrastructure: lifecycle interfaces for multisite and uninstall #34 (rulings of 2026-10-23): the new multisite and uninstall lifecycle edges let exceptions propagate in both debug modes, after restoring the site context. That is an approved exception to principle 10. Those edges stay outside every boundary proposed here, and they are registered with plain add_action(), never through a Hooks wrapper.
    • infrastructure: services cannot choose the priority of their delayed registration #36, merged in Let delayed services choose their registration priority #154: a delayed service registers at its declared priority, unless its dependencies are only ready after that slot has passed. It then registers at the dependency-resumption point (ServiceBasedPlugin.php:725-731, :747-762). The boundary below sits inside maybe_register_service(), so either path is covered the same way.
    • Principles: 4 (hooks are the integration mechanism, so anything we add is a thin layer over them and never a parallel event system), 3 and 5 (injected collaborators with built-in defaults), 9, 10, 11 (idempotent steps), 13 (no public lookup of services) and 14 (the samples teach). Every class file declares strict_types=1 (hard rule).
    • infrastructure: WP-CLI commands as a capability interface #35 is blocked on this issue, for its acceptance criterion "errors while registering a command follow the exception boundary".

    WordPress facts the design rests on (6.9.4)

    1. Callback identity. _wp_filter_build_unique_id() (plugin.php:1000-1021) keys a string callback as itself, a closure or invokable object by spl_object_hash(), [ $object, 'm' ] as the object's hash plus m, and [ 'Class', 'm' ] as Class::m. Actions and filters share that key space. WP_Hook::add_filter() stores one entry per key and priority, and re-adding an existing entry replaces it in place, accepted_args included (class-wp-hook.php:87-94). remove_filter() needs the same callback and the exact priority (:193-217). has_filter() gained a $priority argument in 6.9 (:240-262). A wrapper is a different callable. After a wrapped add, has_filter( 'the_content', [ $service, 'prepend_post_header' ] ) and remove_filter() with that callback both return false (prototype).
    2. Arguments. A callback registered with accepted_args = 0 is called with no arguments, and anything else gets the arguments sliced to its count (class-wp-hook.php:338-344). A filter value is replaced by each callback's return value, including the return value of a zero-argument callback. do_action( 'x' ) without arguments passes '' (plugin.php:515-516). do_action_ref_array() and apply_filters_ref_array() can pass references.
    3. Type coercion. class-wp-hook.php does not declare strict_types, so WordPress calls callbacks in coercive mode: a string parameter accepts 123. A call from a file with strict_types=1 is strict, through call_user_func_array() too (prototype, 7.4 and 8.3). Any wrapper in src/ therefore calls callbacks more strictly than WordPress does.
    4. No try/finally in WP_Hook. An exception that leaves a callback skips every later callback on that hook, other plugins' included. If something further out catches it, that hook's nesting level and $wp_current_filter are left behind for the rest of the request. In the prototype, doing_filter( 'x' ) stays true and current_filter() keeps returning x after the catch. Two consequences follow:
      • the catch has to sit inside each callback, never around do_action() or apply_filters();
      • a catch can only fully restore WordPress's state when the exception comes from the plugin's own code. When it comes from a listener on a hook that this code fired, the catch still saves the page, but that nested hook's bookkeeping stays wrong. This already applies to the view system today, for example when a template calls a template tag whose filter throws. No catch can repair WP_Hook's private state, and architecture.noGlobalState rules out patching $wp_current_filter.
    5. What production gets today. An uncaught exception is an E_ERROR fatal, which PHP logs if log_errors is on. WP_Fatal_Error_Handler then usually shows the critical error screen (class-wp-fatal-error-handler.php:31-64: not while scraping an activation sandbox or in maintenance mode, and only if headers are not sent or in the admin). On single-site only (:54), recovery mode can email the administrator or pause the plugin. That needs the error to be attributable to a plugin file and to happen on a protected endpoint (class-wp-recovery-mode.php:168-200). An exception that is caught and swallowed loses all of that. Principle 10 rules out error_log() as a replacement.
    6. Activation and deactivation. activate_plugin() fires activate_{$plugin} (wp-admin/includes/plugin.php:703) before it saves active_plugins (:714), so an exception means the plugin is not activated. deactivate_plugins() fires deactivate_{$plugin} inside its loop (:826) and saves the option only after the loop (:845). An exception there keeps this plugin active, and also every other plugin in the same bulk action.

    Where exceptions leave the plugin today

    Edge Code Today
    Registration at plugins_loaded register() ServiceBasedPlugin.php:307-314 → register_services() :329 (injector configuration :355, services filter :391, normalization :397, scheduling) escapes
    Delayed registration closure :749-759 → maybe_register_service() :782-799 escapes
    Resumption of pending services closure :512-514 → register_pending_services() :482, which asks is_needed() (:555) and can throw FailedToResolveDependencies (:562, :649, :670) escapes
    Activation, deactivation basic-scaffold.php:119-131 → activate() :195 / deactivate() :217, both of which call register_services() first escapes
    Services' own callbacks SampleBackendService.php:76, SampleLoopService.php:113 view failures contained (#150); anything else escapes
    #34's new edges not implemented yet ruled: propagate

    Part 1: the policy (the same in every option)

    One small infrastructure class, ExceptionBoundary, which is final. It takes the name of the diagnostic action and an optional ?DebugMode that falls back to WordPressDebugMode (principle 3). It has one method, contain( Throwable $failure, FailureSite $site ): void:

    • Debug mode on: rethrow $failure unchanged (question 5).
    • Debug mode off: report it (Part 5) and return. The caller then falls back.

    FailureSite is a small value object that says where the failure happened: a service ID, or a hook, a priority and a description of the callback. That follows principle 8 instead of passing a bare string.

    It catches Throwable, as the view system does. The most likely production failure is a TypeError caused by loosely typed WordPress data (principle 9), and that is an Error, not an Exception. Fatal errors such as memory exhaustion or a timeout cannot be caught at all.

    One instance per plugin. ServiceBasedPlugin gets an optional constructor parameter for the boundary, placed after the runner and injector factory that #34 adds. Without one, it builds the default with static::HOOK_PREFIX . 'failure_contained'. It then delegates ExceptionBoundary to that instance in the injector, exactly as it already does for Injector (:365-368). So registration and service callbacks share one policy, and a custom DebugMode reaches both.

    Fallbacks. A filter returns its first argument as it received it (null if there was none). An action does nothing. A filter registered with accepted_args = 0 still needs that first argument, so its wrapper is registered with at least one argument and calls the callback with none (prototype: a throwing zero-argument filter returns 'original').

    Part 2: the infrastructure's own edges (independent of Part 3)

    Placement: inside the methods, not around the callbacks. register() keeps adding [ $this, 'register_services' ], so its identity, and any remove_action() against it, stays as it is. The catches go inside register_services(), register_pending_services() and maybe_register_service().

    The plugin's own filters stay outside the try. A listener that throws on services, bindings, arguments, shared_instances or delegations is another plugin's code. Catching it would leave that filter's state wrong (fact 4). So apply_filters() runs outside the try, and such a failure propagates as it does today. The boundary contains what the plugin itself does with the result: validating, configuring and scheduling it.

    Failure scope, for every call into a service class:

    Call Where Scope with debug mode off
    Injector configuration and normalization of the filtered map :355, :397 the whole run
    Unknown dependency IDs, cycles, dependencies that can never be registered :562, :649, :670, :1253 the whole run
    get_dependencies(), get_registration_action(), get_registration_priority() :551, :673, :701, :738-743, :1253 the whole run: these declare the graph, so a throwing one is a configuration error
    is_needed(), on both paths :555 (pending), :789 (scheduled) that service
    Construction, including delegations :793 that service
    register() :797 that service
    • The whole run: the services registered so far stay registered, and nothing more is scheduled in this request. The plugin keeps the contained failure (see lifecycle below).
    • That service: it is marked as failed for the request and never retried (principle 11). Its dependents are skipped as "depends on a failed service", and are not reported as FailedToResolveDependencies. That goes for the pending path too.

    Registration state, not container membership. Today the service goes into the container (:794) before register() runs (:797), and container membership is the only guard against registering twice (:784-786). If register() throws part-way, the service stays in the container, so its dependents count it as registered and register against a half-registered service. Moving the insertion after register() alone would open a re-entrancy hole: a register() that causes its own registration action to fire again would register the service a second time. So each service gets an explicit state: registering (set before any of its code runs), registered and failed. A service enters the container only once it is registered (question 3). Hooks that a failed register() had already added stay attached, because WordPress has no transaction to roll back. That gets documented.

    Covered without extra work: the delayed and resumption closures, because they go through maybe_register_service() and register_pending_services(). Not covered: lazy services (those that are not Registerable) are built when something retrieves them, and whatever retrieves one is responsible for its failure.

    Lifecycle edges propagate in both modes (question 2), the same policy #34 approved for the scoped edges. Under #34's precedence ruling, one event reaches a given service through either the legacy interface or a scoped one. Two failure policies for one event would make the outcome depend on which interface the service happens to implement.

    • activate() and deactivate() let their services' exceptions through. For activation, fact 6 makes that the right outcome: the plugin stays inactive and the administrator sees the error. For deactivation the cost is real: a throwing deactivate() keeps the plugin active, together with the rest of a bulk deactivation. The ways out are fixing the cause, recovery mode (single-site only), or removing the plugin directory.
    • When activate() or deactivate() calls register_services() (:196, :218), registration failures propagate as well.
    • A failure that was contained earlier in the same request is not lost. register_services() bails out on its second call (:341-345). So if registration failed and was contained at plugins_loaded, a later deactivate() in the same request would run over an incomplete map without noticing. Instead, the plugin keeps the contained failure, and activate() and deactivate() rethrow it before dispatching anything.
    • The bridges in basic-scaffold.php stay one-line delegations. The text that currently says the bridge is where exceptions get caught (docs/design-principles.md:267-272, docs/patterns.md:505-510) changes to say that lifecycle exceptions propagate on purpose.

    Part 3: services' own callbacks

    A. Keep direct WordPress hooks, with no general boundary (today's code). Services call \add_action() directly, and only view failures are contained.

    • Fits principles 4 and 14 best: the samples are plain WordPress, and has_action(), remove_action() and WordPress's type coercion all work as usual.
    • Costs: any failure outside a view still takes the request down in production, so principle 10 stays partly unmet, and the docs keep saying so.

    B. Direct hooks, plus an explicit guard inside each callback. Callback identity is untouched, and the fallback is visible where it applies:

    public function prepend_post_header( string $content ): string {
    	return $this->guard->filter(
    		$content,
    		fn(): string => $this->view_factory->create( 'views/test-loop-service' )
    			->render( [ 'post' => $this->post ] ) . $content
    	);
    }
    • Fits: identity, has_*, remove_*, priorities, accepted_args and coercion of the callback's own parameters all stay pure WordPress.
    • Costs: every callback repeats the guard, which is the kind of repeated cross-cutting code the core idea says the infrastructure should own. A forgotten guard fails silently, and a rule can hardly tell which callables are callbacks. Subsystems may only depend on infrastructure interfaces (architecture.dependencyDirection), so the guard needs an interface of its own as well.

    C. An injected Hooks collaborator (recommended). It wraps each callback in the boundary. It is deliberately narrower than the WordPress API, not a one-to-one mirror:

    interface Hooks {
    	public function add_action( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 ): void;
    	public function add_filter( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 ): void;
    	public function remove_action( string $hook_name, callable $callback, int $priority = 10 ): bool;
    	public function remove_filter( string $hook_name, callable $callback, int $priority = 10 ): bool;
    
    	/**
    	 * @param int|false $priority As in WordPress 6.9.
    	 * @return int|bool As in WordPress: the lowest priority, or whether it is
    	 *                  registered at $priority.
    	 */
    	public function has_action( string $hook_name, callable $callback, $priority = false );
    	public function has_filter( string $hook_name, callable $callback, $priority = false );
    }

    The differences from WordPress, on purpose:

    • add_*() returns nothing, because WordPress always returns true.
    • has_*() without a callback does not touch identity, so services keep calling \has_action( 'hook' ) directly.
    • Callbacks are typed callable, because the wrapper has to call them. A speculative removal of a non-callable just returns false on the WordPress side and gives the plugin no reason to support it.

    The sample service changes in two places, and the callback stays as it is:

    public function __construct( ViewFactory $view_factory, WP_Post $post, Hooks $hooks ) {
    	$this->view_factory = $view_factory;
    	$this->post         = $post;
    	$this->hooks        = $hooks;
    }
    
    public function register(): void {
    	$this->hooks->add_filter( 'the_content', [ $this, 'prepend_post_header' ] );
    }

    The composition root binds Hooks::class => GuardedHooks::class and shares GuardedHooks. Sharing is required, not an optimization: remove_* and has_* only find a wrapper through the same instance that added it. GuardedHooks receives the plugin's ExceptionBoundary through the injector delegation from Part 1. The infrastructure's own callbacks and #34's lifecycle edges keep calling WordPress directly.

    What the implementation has to get right:

    • One wrapper per WordPress entry. GuardedHooks keys its wrappers by (hook, priority, callback identity), built as _wp_filter_build_unique_id() builds them, so actions and filters share the key space as they do in WordPress. Each wrapper is a small invokable object that holds the callback, the kind (action or filter) and accepted_args. Re-adding the same callback updates those values and calls WordPress again with the same wrapper. WordPress then replaces the entry in place, keeping its position and updating accepted_args (fact 1). Without that reuse, every call would add a fresh wrapper and a second entry, and architecture.compositionRootContracts would report register() as not idempotent. That existing gate therefore enforces the reuse.
    • Lookup in priority order. has_*() checks the wrappers in ascending priority, so it returns the lowest priority, as WordPress does, and not the first one added.
    • What other code can no longer see. has_filter() or remove_filter() called with the original callback no longer finds it. Principle 13 already keeps service instances out of reach of other code, so outside code can only have relied on this for string or static callbacks. Tests that assert has_action( …, [ $service, 'method' ] ) need to change; the two in the scaffold are tests/php/Integration/SampleBackendServiceTest.php:66 and SampleLoopServiceTest.php:51.
    • Accepted arguments. The wrapper is registered with max( 1, $accepted_args ) and hands the callback exactly $accepted_args arguments.
    • No by-reference parameters. A wrapper that takes its arguments by value silently loses the change made through a by-reference parameter: in the prototype, do_action_ref_array( 'x', [ &$list ] ) left $list empty. A wrapper that takes them by reference emits a warning on every ordinary call, and a wrapper that switches by reflection still gets mixed parameter lists wrong. Core passes references almost only for objects, which need no reference at all. So GuardedHooks rejects a callback with a by-reference parameter, with an InvalidArgument naming it. During registration, that is a failure of that one service. The pattern says to take the object, or to return the value from a filter.
    • Stricter types (fact 3). A wrapper in src/ calls the callback in strict mode, so a string $content parameter given 123 fails, where WordPress would have converted it. In production that failure is contained and the filter returns its input. In debug mode it is a TypeError. That is in the spirit of principle 9, but it is a behaviour change for existing callbacks, and it needs its own yes (question 1). The alternative, calling from a file without strict_types, breaks a hard rule.
    • Actions versus filters. WordPress does not know whether a hook is an action or a filter; the method called decides the fallback. A filter added through add_action() would fall back to null. The docs say so.
    • Hooks added inside a callback. These behave as in WordPress, because the wrapper is a normal callback. A callback added to the running hook at a later priority runs in the same pass (prototype). In feature subsystems, architecture.hooksInLifecycleMethods already restricts adding hooks to the lifecycle methods, and C applies that rule to Hooks calls as well.

    Fits: principle 10 for every service callback, with no try/catch in services (the core idea); principles 3 and 5 (injected and shared, with a default); principle 4 (a thin layer, not an event system); principle 14, since the sample reads almost like plain WordPress. Costs: one more constructor parameter per hooking service, the identity caveat, strict typing, no by-reference parameters, and a little bookkeeping per added callback.

    D. A capability declaration. For example HasHooks::get_hooks(): array returns Hook value objects, and the plugin adds them, wrapped.

    • Fits: the infrastructure owns everything, and services need no extra dependency. Registration is also all-or-nothing, because hooks are only added once the declaration has been returned.
    • Costs: it is a second way to add hooks next to register(). Hooks that are conditional or computed at runtime are awkward to declare. It has the larger public surface (an interface and a value object), and it has the same identity, typing and reference costs as C. For teaching material, two ways of doing the most common thing is the largest cost of all.
    A B C D
    Contains callback failures views only where guarded all all
    has_* / remove_* with the original callback yes yes through Hooks through the plugin
    WordPress's type coercion and by-reference parameters yes yes no no
    Code in each callback none a guard none none
    Runtime and conditional hooks yes yes yes awkward
    New public API none guard interface Hooks, GuardedHooks interface, value object
    Change for existing services none each callback constructor and add_* calls rewrite register()

    Part 4: output and partial output

    The boundary does not buffer output. Buffering every action callback would break callbacks that open a buffer on purpose and leave it open: whole-page post-processing started at template_redirect is the common case, and streaming output and early headers are others. architecture.outputOnlyThroughViews already means a service only prints the direct result of rendering a view, and each view buffers its own template and returns all of its output or none of it (#30, #150). So the worst partial output is the earlier echo statements of a callback that fails half-way. The patterns entry teaches one echo per callback, of one parent view that renders its partials. A partial that fails then leaves only its own place empty, as it already does today.

    Part 5: is a production diagnostic hook justified?

    Yes, I think so. Today a production failure usually shows up in PHP's error log and in WordPress's fatal error handling (fact 5). Containing the failure removes that. Without a replacement, a contained failure leaves no trace at all, which makes the site less observable than it is today. A prefixed action, mwpd.basic_scaffold.failure_contained, passing the Throwable and the FailureSite, is the WordPress-native way (principle 4) for a logging plugin or Query Monitor (#38) to pick it up. It is public API under principle 13, built from HOOK_PREFIX and checked by architecture.prefixedNames.

    A listener that throws is another plugin's bug. The boundary does not catch it: catching it would leave the action's own state wrong (fact 4), and there is no way to report a failing reporter anyway. The failure propagates as an ordinary uncaught exception would today. A re-entrancy guard keeps a failure inside a listener from reporting itself again. The alternative is an injected FailureReporter with a no-op default. It is easier to replace in tests, but only reachable from the plugin's own composition root. I prefer the action.

    Compatibility, teaching cost and enforcement

    • Part 2 is a behaviour change. With debug mode off, which is what Brain Monkey tests see because WP_DEBUG is undefined, registration exceptions no longer propagate. Tests that expect them have to switch debug mode on. In tests/php/Unit/ServiceBasedPluginTest.php, that is 12 of its 13 expectException() cases; the remaining one (:787-793) is an injector failure after registration and is unaffected. A generated plugin with its own such tests needs the same change. The optional constructor parameter adds API, but it changes the constructor's line in tests/php/Architecture/infrastructure-api.txt, which goes through the snapshot's review. breaking, for the production behaviour.
    • Part 3, option C. For each service that adds hooks: one constructor parameter and property, and each \add_* call becomes $this->hooks->add_*. Callbacks with by-reference parameters are rewritten. Tests that check hooks against the original callback use Hooks instead (two in the scaffold). The composition root shares GuardedHooks and binds Hooks to it. Other code that removed one of the plugin's string or static callbacks no longer can. If the rule below ships with it, every direct hook call in a generated plugin's subsystems fails composer lint until it is migrated, so that is breaking too.
    • Enforcement for C, with no gate weakened:
      • a new rule (working name architecture.hooksThroughBoundary) reports add_action(), add_filter(), remove_*(), and has_*() with a callback, when called directly in feature subsystems. Its message says to inject Hooks instead. The infrastructure and the composition root stay exempt;
      • noHooksInConstructor and hooksInLifecycleMethods also cover calls on a Hooks-typed value;
      • prefixedNames checks Hooks::add_action() calls for wp_ajax_ actions the way it checks add_action() today. Otherwise moving AJAX handlers to Hooks would quietly drop that check;
      • compositionRootContracts already checks idempotence by callback identity, which catches a GuardedHooks that does not reuse its wrappers;
      • the API snapshot grows by the new types, and the reviewed constructor line changes with Part 2.
    • Teaching cost. Every hook example in the book and the samples changes shape. Readers have to learn three things: why a hook added through Hooks does not show up in has_action() with the original callback, why the callback gets strict types, and why by-reference parameters are out. In return, principle 7's table gets a row ("one failing callback takes the whole page down" → "Hooks contains it"), and principle 10 can drop its "other callbacks do not yet" caveat. A new patterns entry, "I need a hook callback that fails safely", explains it.

    Verification plan for the implementation

    Brain Monkey does not run callbacks. So the unit tests capture the wrapper that add_filter()/add_action() receives and call it the way WP_Hook does, with the arguments sliced. One integration test loads WordPress's real WP_Hook behaviour through a dev-only fixture, so that identity, in-place replacement and nesting are checked against core and not against a stand-in. Whether that fixture is worth adding is a detail for the implementation brief.

    • Hooks, with debug mode on and off: a throwing action and a throwing filter. Debug mode rethrows the same instance. Production returns the first argument as received for a filter and nothing for an action, and fires the action once with the right FailureSite.
    • A zero-argument filter, an action fired with no arguments, and accepted_args slicing. A callback with a by-reference parameter is rejected. A coercible scalar (123 for a string parameter) fails in strict mode and is contained in production.
    • Identity: the same callback added twice leaves one entry; adding it through the other method or with another accepted_args updates the entry in place; remove_* and has_* through Hooks work at the right priority; has_* returns the lowest priority; a different priority is a different entry.
    • Registration, with debug mode on and off: a service whose is_needed() (on the scheduled path and on the pending path), constructor or register() throws, next to an unrelated service. Production: the unrelated service registers, the failed one is not in the container and is not retried, its dependents are skipped without FailedToResolveDependencies, and the action fires. Debug mode: the original exception propagates. Then the whole-run cases: an invalid services filter result, a throwing get_dependencies(), a cycle, a delayed service failing at its action, a resumption failing. A throwing listener on the services filter propagates in both modes.
    • Re-entrancy: a register() that fires its own registration action again registers the service once.
    • Lifecycle: activation and deactivation propagate in both modes, including registration failures reached through them. A failure contained at plugins_loaded makes a later deactivate() on the same instance throw it. infrastructure: lifecycle interfaces for multisite and uninstall #34's lifecycle tests stay unchanged.
    • A throwing diagnostic listener propagates and does not report itself again. A callback that opens an output buffer on purpose keeps it open.
    • composer test on PHP 7.4 and 8.3, and composer lint on 8.3, as in CI.

    Questions for the ruling

    1. Service callbacks: A, B, C or D? If C:
      • does the rule that reports direct hook calls in subsystems ship together with it (breaking), or does C start as opt-in, with the rule following later?
      • do you accept strict typing for wrapped callbacks, and rejecting callbacks with by-reference parameters?
    2. Legacy activation and deactivation: propagate in both modes, consistent with infrastructure: lifecycle interfaces for multisite and uninstall #34, and document the bulk-deactivation consequence? Or contain deactivation failures in production, so that a broken plugin can always be deactivated, at the cost of two failure policies for one event?
    3. Registration state: does a service enter the container only once its register() has returned, with an explicit registering/registered/failed state guarding against re-entry?
    4. Production diagnostics: add the failure_contained action? And should the view system (Degrade view creation and rendering failures in production #150) fire it too? That would be a separate, small behaviour change to an approved policy, so it needs its own yes or no.
    5. Debug mode: rethrow the original exception unchanged (recommended: exception types stay stable for callers and tests, and PHP's own output already shows the frame of the callback), or wrap it in a new exception that names the hook or service and keeps the original as its cause?
    6. Staging: Part 2 as its own issue first, then Part 3 as a second one, each with its own compatibility ruling?
    7. infrastructure: WP-CLI commands as a capability interface #35: is its criterion "errors while registering a command follow the exception boundary" met by Part 2's per-service registration boundary? Command execution under WP-CLI would then propagate, because the CLI is an operator surface and not the end user. If yes, infrastructure: WP-CLI commands as a capability interface #35 is blocked only by Part 2's issue.

    Recommendation (separate from approval)

    • Stage 1, its own issue, breaking: Part 1 and Part 2. That means ExceptionBoundary and FailureSite shared through the injector, containment per service on the request path with the scope table above, explicit registration state, the failure_contained action, rethrowing unchanged in debug mode, and propagation for every lifecycle edge, including a failure that was contained earlier in the request. This is the highest-value step: today a single broken service at plugins_loaded takes every page of the site down in production. It changes nothing about how services add hooks.
    • Stage 2, its own issue, after stage 1: option C, adopted by both samples, with the new rule and the prefixedNames extension shipping at the same time. The scaffold should then teach one way to add a hook. C is the option with the most fine print (identity, strict types, references). If plain-WordPress readability matters more to you than containing callback failures, A is defensible: the view work already covers the failure the samples are most likely to hit.
    • I would not route views through the action without a separate yes (question 4). I would also not attempt to roll back hooks that a failed register() had already added.
  5. added
    needs: decisionBlocked on a maintainer ruling, not on code. State the question and options.
    and removed
    agent-readyContext and acceptance criteria are complete enough for an agent to take this unattended.
    on Oct 23, 2026
  6. removed their assignment
    on Oct 23, 2026
  7. schlessera commented on Oct 23, 2026

    @schlessera
    MemberAuthor

    Handing off: this issue now waits on a maintainer ruling on the seven questions in the proposal above. To resume, record the decision as a **Decision (maintainer, <date>):** comment and fold it into the body. If staging is approved (question 6), file stage 1 and stage 2 as their own issues with their own compatibility rulings, and point #35's blocker at the stage 1 issue. Then remove needs: decision here. I have released my assignment.

  8. added
    breakingChanges an interface or convention generated plugins rely on. Needs a ruling before code.
    on Oct 23, 2026
  9. schlessera commented on Oct 23, 2026

    @schlessera
    MemberAuthor

    Triage (2026-10-23): Preserved the posted Hooks/boundary proposal and folded its exact unresolved policy/compatibility questions into the body; corrected moved registration anchors and reconciled implemented #34/#36/#27. Added breaking for proposed behavioural/API migrations, without approving them.

  10. schlessera commented on Oct 23, 2026

    @schlessera
    MemberAuthor

    Triage (2026-10-23): Repaired registration anchors at main 61a9b00 and reconciled implemented #38/#163. The posted boundary/wrapper questions remain unapproved; existing opt-in history and disabled-path requirements must be preserved.

  11. schlessera commented on Oct 24, 2026

    @schlessera
    MemberAuthor

    Triage (2026-10-24): Repaired registration anchors and reconciled the implemented asset boundary from #177. General Hooks/lifecycle/state/reporting choices still need the posted maintainer rulings; the existing scoped-lifecycle, view and asset policies remain authoritative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: infrastructuresrc/Infrastructure: services, injector, views, autoloader. What generated plugins build on.breakingChanges an interface or convention generated plugins rely on. Needs a ruling before code.needs: decisionBlocked on a maintainer ruling, not on code. State the question and options.priority: p3Someday. Needs a driving use case before it starts.type: spikeTime-boxed investigation. The deliverable is a written decision, not code.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions