Page MenuHomePhabricator

[Data Persistence Design Review] Article Feature counts per page
Open, MediumPublic

Description

Proposal

Serve article feature counts for the Attribution API (IR2.1.2d).

The attribution API requires reference and citation counts. We propose a more generic solution to develop a data product that outputs all available article features in mwparserfromhtml.

This ticket is to approve design and provision storage for article feature counts per page revision — the reference/citation count signal of the Attribution API — as a new cached artifact in the Linked Artifact Cache (LAC / hoarde), keyspace linked_artifacts on the RESTBase Cassandra cluster.

A new lambda service (ArticleFeatureCounts) fetches the HTML of a page revision from the MediaWiki REST API and computes absolute article feature counts with mwparserfromhtml (Research). LAC stores the lambda's output verbatim and serves it. On every page change, a MediaWiki JobQueue job warms the cache for the new revision, so reads are normally cache hits. The Attribution API reads the artifact from LAC and exposes reference_count in the trust_and_relevance object.

┌─────────────────────────────────────────────────────────────────────────────┐
│                      UPSTREAM (canonical source)                            │
│  MediaWiki: page HTML for (wiki_id, page_id, revision_id)                   │
│  PageLatestRevisionChangedEvent  →  mw.job.FeatureCountsUpdate (JobQueue)   │
│  Side output: feature-counts event stream → Data Lake  (historical analysis)│
└─────────────────────────────────────────────────────────────────────────────┘
                                    │ GET, Cache-control: no-cache (warm)
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                   SERVE + STORE (SRE Data Persistence)                      │
│  Linked Artifact Cache (hoarde, `linked-artifacts`)                         │
│    GET /revisions/v1/page_feature_counts/{wiki_id}/{page_id}[/{revision_id}]│
│    Cassandra: linked_artifacts.page_feature_counts  (RESTBase cluster)      │
│                     │ cache miss (gRPC)                                     │
│                     ▼                                                       │
│  ArticleFeatureCounts lambda → MW REST HTML → mwparserfromhtml → counts     │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  MediaWiki Attribution API  →  clients (Wikimedia Enterprise, community     │
│  tools, reusers).                                                           │
└─────────────────────────────────────────────────────────────────────────────┘
Terminology
TermMeaning
Attribution APIMediaWiki REST module that returns attribution-related page metadata.
CitationAn inline [1]-style marker linking a statement to a source (typeof mw:Extension/ref in HTML). Not unique — the same reference can be cited many times.
ReferenceA unique citation — an entry in the References list ({{Reflist}}, li#cite_note-* in HTML). Reference groups (e.g. Notes) count as references.
SourceA unique reference target (one book, one website domain). Not yet computable — mwparserfromhtml does not produce it; Research work is needed. Out of scope for launch.
Feature countsAbsolute counts of page features in a revision rendering: references, citations, wikilinks, sections, media, infoboxes, etc.
LACLinked Artifact Cache, the linked-artifacts service (hoarde), owned by SRE Data Persistence. Durable storage with caching semantics for derived data linked to MediaWiki entities.
LambdaThe service LAC calls on a cache miss to compute the artifact.
Cache warmA GET to LAC with Cache-control: no-cache, which forces the lambda to run and the result to be stored.
mwparserfromhtmlResearch library that extracts page features from MediaWiki HTML.
Data model

LAC's table shape is fixed by hoarde — one table per artifact namespace, all with the same columns (schema.cql):

ColumnTypeDescription
wikiTEXTWiki database code (e.g. enwiki); partition key component
pageBIGINTMediaWiki page_id; partition key component
revisionBIGINTMediaWiki rev_id; clustering key, DESC
contentBLOBThe lambda's output, stored verbatim (JSON, see below)
last_modifiedTIMESTAMPWhen the artifact was computed and stored
metadataMAP<TEXT,TEXT>Content type, and the computing software's name/version and language

Artifact content (JSON in content):

{
  "software_info": {"name": "mwparserfromhtml", "version": "1.x.y", "algorithm": "WikiStew?"},
  "language": "en",
  "counts": {
    "reference": 187,
    "citation": 243,
    "external_link": 64,
    "wikilink": 512,
    "section": 14,
    "heading": 13,
    "category": 22,
    "media_img": 9,
    "infobox": 1,
    ...
  }
}

mwparserfromhtml's WikiStew currently exposes ~21 feature types.

Access pattern
  • Reads (cache hit): single-partition Cassandra point read with WHERE wiki = ? AND page = ? AND revision = ?. Served over HTTP by LAC — GET /revisions/v1/page_feature_counts/{wiki_id}/{page_id}[/{revision_id}].
  • Reads (cache miss): LAC calls the lambda, stores the result, and returns it. The Attribution API does not want to block on this — see T435557: Handling Flagged Revs for Reference Counts in Attribution API and T433607: Provide a way to query the LAC without triggering a compute job on a cache miss (return null or use Cache-control: only-if-cached, and let the warm happen asynchronously).
  • Writes: one write path only, from LAC itself. Each store is INSERT (wiki, page, revision, …) plus a range delete of revision < ?, so a partition normally holds a single row — the newest revision computed.
  • Cardinality: one partition per (wiki, page); ~1 row per partition. May hold more than one revision ocasionally due to flagged_revs accessing older stable revision.
  • Rate of change: one write per in-scope page change (cache warm), plus one write per cache miss.
Data Size

Row size, storing all ~21 feature counts (uncompressed, before Cassandra overhead):

ColumnEstimated sizeExplanation
wiki~8 bytesMost wiki IDs are ≤10 chars
page8 bytes64-bit integer
revision8 bytes64-bit integer
last_modified8 bytesTimestamp
metadata~60 bytesLambda-controlled; content type, and optionally software version
content~425 bytesCompact JSON of all 21 counts: counts block ≈ 323 B + software_info and language ≈ 102 B
Total per row~520 bytes

The content figure is the serialised byte length of the JSON document shown above, with all 21 WikiStew feature keys present. The 21 keys average 7.9 characters, so a "key":value, entry costs ~15 bytes (13 B with single-digit counts, 17 B with five-digit ones) — the count magnitudes barely matter. Pretty-printing with spaces adds ~50 B; the numbers here assume compact JSON.

Volume by rollout scope (one row per page):

ScopePages~520 B/row (all features)
enwiki, main namespace~7M~3.6 GB
All Wikipedias, main namespace~65M~34 GB
All wikis, all namespaces (not in scope)~690M~357 GB
Growth

Growth is bounded by new-page creation, since existing pages reuse their partition. The all-wiki, all-namespace measurement in T427442: [Data Persistence Design Review] Editor count per page (Attribution API) is +4.4M to +6.3M new (wiki, page) pairs per month, which is an upper bound for the Wikipedia main-namespace subset here. Edits to existing pages do not add partitions; they replace the row (and leave a range tombstone).

Performance
MetricTarget
P50 read latency (cache hit)TBD
P95 read latency (cache hit)TBD
P99 read latency (cache hit)TBD
Read throughput (steady state)TBD
Read throughput (peak)TBD
Write throughputTBD — one write per in-scope page change, plus cache misses

What we know:

  • Latency budget: the whole Attribution API round trip must be ≤ 400 ms. The reference count is one field inside that, so a cache hit must be comfortably inside it.
  • Read shape: Read volume upper bound roughly tracks the edit rate, concentrated on recently edited and popular pages. Community tools and other reusers add a long tail.
  • Cache miss cost: an HTML fetch plus a parse — hundreds of milliseconds or more, which does not fit the 400 ms budget. This is why every edit warms the cache, and why misses must be handled without blocking (T435557: Handling Flagged Revs for Reference Counts in Attribution API, T433607: Provide a way to query the LAC without triggering a compute job on a cache miss).
  • Staleness tolerance: requirements allow counts up to 24 hours stale, and warming makes them near-real-time in practice.
  • Write shape: steady rather than bursty, one write per in-scope page change.
Retention and expiration
  • Only the ~current revision's counts are needed. Older revisions are range-deleted on each store, and are recomputable on demand.
  • No fixed expiration date — this is an ongoing product signal tied to the Attribution API lifecycle.
Dependencies
  • Upstream: MediaWiki REST API (HTML), MediaWiki JobQueue + PageLatestRevisionChangedEvent (warming), mwparserfromhtml (Research).
  • Downstream: MediaWiki Attribution API → Wikimedia Enterprise, community tools and reusers.
  • Degradation: if LAC or the lambda is unavailable, the Attribution API omits the field or returns null; Enterprise has a fallback path (counting citation identifiers themselves).

Decision brief

We will store the artifact in Cassandra on the RESTBase cluster, in the existing linked_artifacts keyspace used by LAC, and serve it through LAC's HTTP API (no Data Gateway). The table follows hoarde's fixed artifact schema:

CREATE TABLE linked_artifacts.page_feature_counts (
    wiki          text,
    page          bigint,
    revision      bigint,
    content       blob,
    last_modified timestamp,
    metadata      map<text,text>,
    PRIMARY KEY((wiki, page), revision)
) WITH CLUSTERING ORDER BY (revision DESC);

Plus the corresponding grants for the linked_artifacts role (puppet/modules/cassandra/templates/users/linked_artifacts.cql.erb) and a hoarde.tables entry in helmfile.d/services/linked-artifacts/values.yaml pointing at the lambda — staging first.

Event Timeline

Eevans triaged this task as Medium priority.Sep 11 2026, 6:03 PM
Eevans added a project: User-Eevans.
Eevans added a subscriber: KOfori.

@AKhatun_WMF thank you (again) for such a clear and concise description of the problem, your proposal and rationale; We should consider adding this (or one of your others) as an example for others to https://wikitech.wikimedia.org/wiki/SRE/Data_Persistence/Design_Review!

We've discussed this in elsewhere, but everything here makes sense to me; I see no issues.

Are we in a position yet to know the timline? In particular, it looks like we have T433607: Provide a way to query the LAC without triggering a compute job on a cache miss as a dependency. That will be a pretty simple change, but for planning purposes, it would still be helpful to know when we need that in place (/cc @KOfori).

Thank you @Eevans!
I have re-read T433607: Provide a way to query the LAC without triggering a compute job on a cache miss comments and I am not completely sure we need anything too complicated here. But I will let you decide. What we need is:

...it might make more sense to also not change the default behavior of LAC yet, and instead have Attribution API set a timeout client-side, after which it gives up on the request, but the async computation still happens.

So from LAC perspective, we just have a really long timeout set (We can start with 60s, same as html fetching flink job, and look for pages that still fail). Per some very rudimentary benchmarks, 2MB big html pages take 10-15 seconds to compute. So LAC computes and saves cache. Client is the one who times out, sets a null or whatever they prefer, and can call LAC again later to look for cached result.

Timeline:
I am expecting lambda to be ready for staging testing this week. And maybe ready for prod deployment ~end of next week. So setting up LAC sometime next week would be great!
Do you expect or want to test connection with lambda before LAC set up work? Or maybe that comes after.

@Eevans a few things I wanted to clarify about LAC

  • We would need content_type: application/json for this table. I believe that is how data is presented to external services from LAC.
  • I initially assumed lambda needs to set a content type in header/metadata. It looks like the lambda returned metadata field is never returned to consumer. What does hoarde expect to be set in the metdata field?
if value, err = Lambda(key, table.Lambda); err != nil {
	promLambdaDurationHistoVec.WithLabelValues(name, "error").Observe(...)
	h.log.Request(r).Log(servicelib_log.ERROR, "Unable to acquire artifact: %s", err)
	newProblem(http.StatusInternalServerError, "Internal Error",
		"Lambda invocation failed (see logs).").WriteTo(w)
	return
}
  • It looks like any error sent is turned into 500 Internal Error. We expect to send revision not found, wiki not found, parser faults etc. Is it ok to call them all 5xx error? For instance if deleted revisions are being called for too many times, we don't want to assume something is wrong with the lambda due to too many 5xx errors. Maybe separating error code classes would be preferred, at the minimum?

Thank you @Eevans!
I have re-read T433607: Provide a way to query the LAC without triggering a compute job on a cache miss comments and I am not completely sure we need anything too complicated here. But I will let you decide. What we need is:

...it might make more sense to also not change the default behavior of LAC yet, and instead have Attribution API set a timeout client-side, after which it gives up on the request, but the async computation still happens.

So from LAC perspective, we just have a really long timeout set (We can start with 60s, same as html fetching flink job, and look for pages that still fail). Per some very rudimentary benchmarks, 2MB big html pages take 10-15 seconds to compute. So LAC computes and saves cache. Client is the one who times out, sets a null or whatever they prefer, and can call LAC again later to look for cached result.

Timeline:
I am expecting lambda to be ready for staging testing this week. And maybe ready for prod deployment ~end of next week. So setting up LAC sometime next week would be great!
Do you expect or want to test connection with lambda before LAC set up work? Or maybe that comes after.

We should deploy first to staging (your lambda service deployed to k8s staging, talking with staging hoarde, which is backed by staging Cassandra). When that checks out Good, we can move the deployment to production (i.e. deploy the production Cassandra table, and Hoarde config changes). So am I to understand you're doing the first of those things (staging) this week, and the latter (production) next? I am out on Friday, and then all next week. so I could probably manage the former (if we can do it on or before Thursday), but the latter would be a problem. I could try to have things ready, and leave it to someone else (@Ottomata ), or we could tackle it the week of the 28th. Let me know.

@Eevans a few things I wanted to clarify about LAC

  • We would need content_type: application/json for this table. I believe that is how data is presented to external services from LAC.

Yeah, you can return the content-type in the metadata attribute of the response struct, but if you don't, Hoarde will default to application/json.

  • I initially assumed lambda needs to set a content type in header/metadata. It looks like the lambda returned metadata field is never returned to consumer. What does hoarde expect to be set in the metdata field?
if value, err = Lambda(key, table.Lambda); err != nil {
	promLambdaDurationHistoVec.WithLabelValues(name, "error").Observe(...)
	h.log.Request(r).Log(servicelib_log.ERROR, "Unable to acquire artifact: %s", err)
	newProblem(http.StatusInternalServerError, "Internal Error",
		"Lambda invocation failed (see logs).").WriteTo(w)
	return
}

The block of code you've quoted will take any gRPC error and turn it into an Internal Server Error. The contents of the error will be logged, but not returned to the client. The client gets a generic 500 error as a JSON-formatted HTTP problem object (see: RFC 9457).

  • It looks like any error sent is turned into 500 Internal Error. We expect to send revision not found, wiki not found, parser faults etc. Is it ok to call them all 5xx error? For instance if deleted revisions are being called for too many times, we don't want to assume something is wrong with the lambda due to too many 5xx errors. Maybe separating error code classes would be preferred, at the minimum?

Good point, that's definitely worth considering. Can you open a ticket so that we can follow up on that? Thanks!

@Eevans a few things I wanted to clarify about LAC

  • We would need content_type: application/json for this table. I believe that is how data is presented to external services from LAC.

Yeah, you can return the content-type in the metadata attribute of the response struct, but if you don't, Hoarde will default to application/json.

Oh, I am sorry, this isn't right; You cannot assign the content-type via the metadata attribute in the response struct. I did have it that way originally, but there is an implicit contract between the client and the lambda, and changing that value would be a violation of the contract (read: it should not be easy to do). So the content-type is a part of the service (Hoarde) configuration (see for example: https://gitlab.wikimedia.org/repos/sre/hoarde/-/blob/main/sample-config.yaml#L37).

Sorry for the confusion.

So am I to understand you're doing the first of those things (staging) this week

Yes, I think its going to flow to next week, but hopefully can start soon.

or we could tackle it the week of the 28th. Let me know.

We can do production week of 28th, yes. SCROLL has some more items left (alerts etc). I think we'd need those before full deployment.

Can you open a ticket so that we can follow up on that?

Here it is: T438201: Hoarde error type needs classification. Not sure what other tasks it should link to or the tags. Feel free to add those. Thanks!

Wanted to ask how we should handle timeouts in Client vs LAC vs Server. Per comment above, Client can set their own timeout, LAC should continue to fetch and cache for future response.

Is it ok to assume LAC will have higher timeout than the service? Asking because I was about to implement caller_dropped error, since LAC will send a timeout value in context. I wouldn't want the service to keep churning while LAC has given up. But, in the service, assuming a 60s timeout for fetch and 2 retries, the total time server *may* spend worst case is 60*3 = 180s. Would LAC have such a big timeout? Seems too big, but also not sure how to reconcile the fact that our timeout won't matter if LAC gives up.

Wanted to ask how we should handle timeouts in Client vs LAC vs Server. Per comment above, Client can set their own timeout, LAC should continue to fetch and cache for future response.

Is it ok to assume LAC will have higher timeout than the service? Asking because I was about to implement caller_dropped error, since LAC will send a timeout value in context. I wouldn't want the service to keep churning while LAC has given up. But, in the service, assuming a 60s timeout for fetch and 2 retries, the total time server *may* spend worst case is 60*3 = 180s. Would LAC have such a big timeout? Seems too big, but also not sure how to reconcile the fact that our timeout won't matter if LAC gives up.

I'm not sure I completely understand your question, but if the client hangs up before the LAC response (i.e. because its timeout is short), you should assume that the artifact will not be cached. In this case, LAC will propagate an error to the lambda, so that it does not continue working. Clients (LAC clients) should harmonize their timeouts with it. If they are unable to block for requests that take longer than some threshold, then they can background the request, or use Cache-Control: only-if-cached after that lands (see: T433607: Provide a way to query the LAC without triggering a compute job on a cache miss). The former would ensure that the artifact has a chance at being cached, the latter causes requests to return immediately (with a status 504) if a value isn't already cached.

When you say "60s timeout for fetch and 2 retries", is this from within the logic of your lambda? Is this the fetch of HTML from mediawiki? Either way, yes 180s would be a very large timeout to use; These timeouts (deadlines in gRPC parlance) are sort of circuit breaker, a guardrail, and 180s is a long time to wait.

if the client hangs up before the LAC response (i.e. because its timeout is short), you should assume that the artifact will not be cached. In this case, LAC will propagate an error to the lambda, so that it does not continue working

Hm, this could be a problem and negate the 'self-healing' feature of LAC. This is a point I was sort of raising in T433607: Provide a way to query the LAC without triggering a compute job on a cache miss, so I'll respond more fully there: T433607#12355443

if the client hangs up before the LAC response (i.e. because its timeout is short), you should assume that the artifact will not be cached. In this case, LAC will propagate an error to the lambda, so that it does not continue working

Hm, this could be a problem and negate the 'self-healing' feature of LAC. This is a point I was sort of raising in T433607: Provide a way to query the LAC without triggering a compute job on a cache miss, so I'll respond more fully there: T433607#12355443

My assumption is that delivery of the cache warm event is reliable. Obviously nothing is entirely reliable, but missed updates should be quite exceptional. If that's not the case, I think we should be talking about what is wrong there, and how to make it right. Additionally, if it is unreliable, then surely so are stream-processing produced artifacts (meaning: what is the alternative?).

If they are exceptional, then the problem is one of timing, a racing read that lands before the warm event has succeeded, in which case use only-if-cached and know that follow-up reads will succeed (at least those that arrive after computation has had time to complete; we cannot serve a result sooner than it can be generated).

TL;DR It sounds like we're looking for an engineering solution to a subset of high-latency lambda requests that overlap with a lost cache warm event. How frequently do we expect that to happen?