Page MenuHomePhabricator

wikipage.content mw.hook doesn't reliably send #mw-content-text to handlers registered as early as possible
Open, Needs TriagePublicBUG REPORT

Description

Steps to replicate the issue:

wikipage.content is broadly used by user scripts so they can be called once the page is ready and again on subsequent updates to the page content. This usage is documented in various places including https://doc.wikimedia.org/mediawiki-core/master/js/Hooks.html which further states:

This includes the ready event on a page load (including post-edit loads) and when content has been previewed with LivePreview.

Unfortunately, there is a race condition that sometimes prevents registered handlers from receiving the ready event on a page load if another user script runs:

mw.hook( 'wikipage.content' ).fire( $content );

slightly before the affected user script registers with mw.hook. This can even happen if the script calling .fire() waits until it itself is triggered by the wikipage.content.

Here's how you can reproduce the issue:

  1. Navigate to https://en.wikipedia.org/w/index.php?title=Test&action=history&safemode=1
  1. Open the JavaScript console and run:
mw.hook('wikipage.content').add(function($element) {
    console.log('Element tag:', $element.prop('tagName'));
    console.log('Element id:', $element.attr('id'));
});

As the safemode environment doesn't run any JavaScript that fires the wikipage.content hook, the expected DIV for the page content is received:

Element tag: DIV
Element id: mw-content-text
  1. Reload the page and run this instead:
// simulate a separate script modifying the document early and quickly
const $newParagraph = $('<p>This is a small paragraph added to the body.</p>').appendTo('body');
mw.hook('wikipage.content').fire($newParagraph);

// register our hook
mw.hook('wikipage.content').add(function($element) {
    console.log('Element tag:', $element.prop('tagName'));
    console.log('Element id:', $element.attr('id'));
});

Now the result is this instead:

Element tag: P
Element id: undefined

and the #mw-content-text hook is never sent.

What happens?:

The problem is that this means "nothing happens" for some user scripts whenever they don't receive the ready event via the #mw-content-text being fired. This issue is very easily reproduced if you have a relatively fast user script that runs .fire() early enough in your common.js. (Because mw.loader.load is asynchronous, reordering items in common.js won't necessarily avoid the issue too.)

I ended up adding a workaround to a user highlighter script that I've been developing because it was happening over 50% of the time on larger pages. The script now tracks whether it's the first time the hook has fired and the $content that is passed is simply ignored if it's the first time the hook has been called.

I suspect this issue is not seen more often because a lot of user scripts simply never run:

mw.hook( 'wikipage.content' ).fire( $content );

on smaller elements. A lot of people probably just reload the page if the issue is only intermittent for them.

What should have happened instead?:

One solution would be to make sure registered handlers always receive the page content (i.e., #mw-content-text) when they register.

(There is a potential less common use case of user scripts registering long after page ready and not necessarily caring about receiving #mw-content-text, but that might be better handled by adding an optional second parameter for .add() to indicate that the handler should only receive new events.)

Notes:

The reason this happens seems to be documented in the code.

https://github.com/wikimedia/mediawiki/blob/97f1ce97e9fcf3b1c59db9ea98fac51b74907730/resources/src/mediawiki.base/mediawiki.base.js#L464:

* Handlers can be added and fired for arbitrary event names at any time. The same
* event can be fired multiple times. The last run of an event is memorized
* (similar to `$(document).ready` and `$.Deferred().done`).
* This means if an event is fired, and a handler added afterwards, the added
* function will be fired right away with the last given event data.

The problem is that behavior is not what is documented and it's not how user scripts actually use the wikipage.content hook.

Event Timeline

taavi subscribed.

MediaWiki-Core-Hooks is about the PHP hook system for extensions and site config, not the separate JavaScript system.

MusikAnimal subscribed.

I think this is a misconception of the wikipage.content hook. It is not restricted to solely #mw-content-text. I've filed T394707: Do something about misconceptions of the wikipage.content hook.

I think this is a misconception of the wikipage.content hook. It is not restricted to solely #mw-content-text. I've filed T394707: Do something about misconceptions of the wikipage.content hook.

I understand that other elements may be sent (and I handle those case in my usage of this hook), but the problem is that scripts are not reliably being sent #mw-content-text from this hook. It's skipped or lost, essentially.

The documentation says "This includes the ready event on a page load". I have trouble reading that as "scripts may never receive any reliable indication that the content is ready" via this hook, especially when #mw-content-text is actually sent most of the time.

If this is a case of "well, the documentation is wrong", then a new hook with reliable behavior that always notifies scripts when the document is ready as well as for subsequent wikipage.content firings is needed. I don't know why this hook wouldn't be the place to do that, though.

@DanielQ Thanks for filing this, your analysis is correct. The way mw.hook works is that only the last call to mw.hook(…).fire() is remembered and forwarded to listeners which are added afterwards (docs). And we definitely have a lot of code that fires the 'wikipage.content' hook without considering that…


We could split the 'wikipage.content' hook into two to resolve this problem:

  1. One hook, which can continue using mw.hook, that would be fired for only the main content of the page. This would include the initial page load, a full-page preview, or after saving the page and reloading its contents.
  2. Another hook, which must use some different mechanism, that would be fired for every little piece of content generated from wikitext. This would include all of the above, plus things like navigating an image gallery, preview of a single talk page comment, displaying edit notices. This mechanism would probably also need a way to remove or update elements when they are replaced (otherwise it would have to hold on to all of the node references forever, and leak memory on long-running pages).

Extensions (or core features) that implement some kind of dynamic content in wikitext would listen to the second hook whenever possible and support all those little bits (the simplest example is the mw-collapsible class in MediaWiki core), while extensions that implement features that only work in the main page content would listen to the first (e.g. VisualEditor's dynamic section edit links, or DiscussionTools's reply links, or anything that for whatever reason keeps some global state).

It seems like this would be a somewhat painful change, requiring someone to review every use of the hook (both the .fire() and the .add() sites).

As an interim step for DiscussionTools, since we're now aware of this issue from T400613 and don't want to have to play whack-a-mole with whatever gadgets and userscripts might want to fire wikipage.content, I've gotten this patch written and merged, which leaves us doing this:

	mw.hook( 'wikipage.content' ).add( mw.dt.init );
	// wikipage.content can't be counted on for initial setup, because gadgets
	// can potentially have fired it with not-the-main-content before we added
	// our hook, and the hook system only remembers the last call for us.
	$( () => {
		// eslint-disable-next-line no-jquery/no-global-selector
		const $content = $( '#mw-content-text' );
		if ( $content.length && mw.dt.initState.firstLoad ) {
			// We're on a page with main page content and DT hasn't initialized yet
			mw.dt.init( $content );
		}
	} );

This fallback is a hack, but since mw.dt.init also checks within itself to make sure that it'll only act on a #mw-content-text or a known set of previews, I think this is fundamentally equivalent to us bootstrapping our way to @matmarex's first option.

Ideally we can get a replacement in core for this and replace the hack with it, rather than winding up with most things that use wikipage.content evolving their own variant of this over time...

I don't think fixing this for just one hook is the answer. mw.hook only firing once for previously-added listeners is magical and rarely useful.

Similar to the event-model, we can make this the responsibility of the listener to decide what to do with already-fired data:

  • mw.add( 'last', ...fns ) - run the last-fired args (as well as future ones). default/status-quo, and equivalent to mw.add( ...fns )
  • mw.add( 'none', ...fns ) - don't run any previously-fired args (just future ones) - similar to what was proposed in https://gerrit.wikimedia.org/r/c/mediawiki/core/+/964933 as mw.fireExisting
  • mw.add( 'all', ...fns ) - run all previously fired args (and future ones)

Change #1174477 had a related patch set uploaded (by Esanders; author: Esanders):

[mediawiki/core@master] mw.hook: Allow hook handlers what to do with already-fired hooks

https://gerrit.wikimedia.org/r/1174477

It is intentional that mw.hook does not have more than "one" memory. The wikipage.content hook in particular, is meant to for for the content area of wiki pages. It can fire multiple times during the lifetime of a web page, for example after an edit preview or after saving an edit with VisualEditor. If a gadget or extension is then loaded, e.g. as module queued by the new content, or by a UI element that loads additional code, it should not be processing now-dereferenced past page content. Additionaly, holding on to such large DOMs would pose a significant memory leak.

The presence of memory is important, as without it, it would not be a stateless and declarative mechanisms for two components to interoperate. The memory aspect means that the code that "fires" data, and the code that handles it, does not need to know about each other, or their load order. This in turn allows is to load all modules concurrently, as fast as possible.

For the use case of tracking events and other sequences of small data, we have mw.track instead. Both mw.hook and mw.track are very simple 10-line JavaScript functions that call an array of functions with a given argument. One is for small data and full history, where subscribers are meant to handle all past events. The other is for handling the "current" state of the interface, reacting only to the current/last data on the page, and where DOM trees can be significant.

The problem is that the wikipage.content hook has inadvertently wandered outside its specified contract over the years, primarily through VisualEditor applying it to partial pieces of content. This violates the contract because it means the next subscriber will fail to process the rest of the page. Of course, giving it full memory here would be counter-productive. It would mean that after saving an edit, new handles will be processing the entire previous revision of the page. On "Live preview" these may be hundreds of revisions each with a >100MB DOM. Likewise, in VisualEditor, one may edit many different templates, or edit them multiple times until you have the desired effect. You can also save an edit and then activate VisualEditor a second time. You need some kind of "reset" here at the very least.

The bottom line is that when firing a hook, the emitting code is responsible giving it an argument that reasonably superseded the previous one. Firing it with only part one (temporary) part of the page, breaks that contract.

On the other hand, when the page has indeed been replaced (after preview, or after VE edit), it is exactly correct that the previous verison is forgotten. That's not merely an optimisation, either, since it is now a documented expectation of wikipage.content that the $content is live and connected to the document. Invoking callbacks with dereferenced DOM nodes would likely cause uncaught errors and break all sorts of code, thus preventing the current version or other hook handlers from running.

There's a few things we can do here. I'd may be start with an inventory of mw.hook().fire calls for wikipage.content that behave this way (is it only VisualEditor?). If it is only one or two, it might be feasible for those handlers to manage an array of relevant nodes and thus pass a jQuery collection that includes both the page and still-relevant ad-hoc nodes outside the content area. Alternatively, if the partial node is passed at a time when it is part of the page, then it could be fixed by passing a reference to the parent instead. Callers already have the responsibility to select/find relevant nodes, so such optimisation should not be needed.

This solution would not work if there are multiple such actors on the same page. But maybe that's not the case?

See also: T349298: "wikipage.content" JS hook: $content should be consistent on live previews

I don't think VisualEditor's usage of the hook is problematic in the sense that this ticket is complaining about. It does fire it with a payload that isn't the main page contents, however it does so extremely late in the page's lifetime, such that I think we can expect anything that actually wanted to respond to the original value would already have done so.

It's probably fair to split hook consumption into two phases:

  1. initial load, where it lets scripts not need to care too much about load-order and dependencies
  2. anytime after that, where it's pretty much just an event system

Outside of edge cases where something is initialized really late, of course.

But maybe that's not the case?

Alas.

For context, the recent issue with DiscussionTools came about because it was expecting that the initial wikipage.content that mediawiki.page.ready fires wouldn't have been overwritten by the time that another script included in the initial pageload via addModules ran.

In this case it was a gadget (XTools) that was most-commonly responsible, but there's enough complaints from people who don't have that one enabled that there's presumably other gadgets/scripts out there causing the same issue.

@DLynch I agree for VE it is likely safe "enough" in practice, and that's presumably why this hasn't come up much over the years. If it works it works.

I should have asked where this came up because the task doesn't specify what happened, but rather what could happen. I assumed it was VE-related.

If I understand correctly, the XTools gadget is firing the wikipage.content hook relatively early on, and thus able to sometimes disrupt the DT hook handler for wikipage.content before it has had a chance to process the page. Is that right?

It looks like that was added in this edit based on a request, interestingly also by @DanielQ, over at T358298: XTools ArticleInfo should fire on wikipage.content after it finishes.

The gadget inserts HTML from this API into page caption (#contentSub). And even though nothing about this HTML is rendered from wikitext or otherwise represents MediaWiki "content", it contains a link to a username (or IP) contributions page, and there is another gadget (UserHighlighterSimple.js) that would like to highlight all usernames on the page. The xtools pageinfo isn't even trying to imitate MW content, eg. no mw-userlink or mw-usertoollinks-contribs class.

It seems to me that xtools should fire its own hook like xtools.pageinfo and for UserHighlighterSimple.js to handle both hooks, rather than fire wikipage.content for this purpose. There are various places on the page where user names may appear. It is by no means guaranteed that they are all in the content area.

Per T360592#10846373, I think this task is about hooks not firing wikipage.content early enough or without the full content. The issue around expectations of that hook is T394707: Do something about misconceptions of the wikipage.content hook. I read them as two distinct issues, but I could be wrong.

XTools no longer fires the wikipage.content hook. The issues it caused were only noticed because that gadget is so popular. There are tons of MediaWiki extensions, on-wiki scripts and gadgets that fire wikipage.content with something other than #mw-content-text. Even Core does (examples: 1, 2, 3). See Global Search and Codesearch.

If I understand correctly, the XTools gadget is firing the wikipage.content hook relatively early on, and thus able to sometimes disrupt the DT hook handler for wikipage.content before it has had a chance to process the page. Is that right?

Yes. The limited memory is a problem, because nothing expects wikipage.content to have had the actual main page content already-forgotten by the time the DOM is ready.

As @MusikAnimal says, this is now a common pattern outside of core. XTools brought it to our attention, but it's widespread enough that I don't think we can trivially stop it happening -- and the use-case of announcing "this thing is formatted-from-wikitext, please adjust it if needed" seems meaningful-and-useful, even though it's a drift from the original meaning of wikitext.content.