Page MenuHomePhabricator

RevertRisk-Wikidata: move serving and stream to Linked Artifacts Cache
Open, In Progress, Needs TriagePublic

Description

The Problem

Three clients ask for a prediction on the same Wikidata revision, and the model computes it three times:

  • Wikimedia Enterprise, querying LiftWing directly.
  • change-prop, driving the prediction stream so the data lands in the Data Lake.
  • RecentChanges, expected next. (after T429049)

That is expensive here: the model is GPU-backed and slow, and adding the second client in July already caused a latency regression for Enterprise (T420883).

Proposal

Adopt the proposed Linked Artifacts Cache architecture in Prep Pantry (https://wikitech.wikimedia.org/wiki/Prep_Pantry/Architectures#Linked_Artifacts_Cache), matching the second diagram in T433699#12211658:

  • revertrisk-wikidata becomes a LAC lambda (KServe v2 over gRPC).
  • A MediaWiki JobQueue precompute job warms the artifact on PageLatestRevisionChanged for wikidatawiki.
  • MediaWiki produces the prediction event from LinkedArtifactPrecomputed, replacing change-prop and removing event production from LiftWing.
  • Enterprise and RecentChanges read from LAC instead of calling LiftWing.

One inference per revision, shared by all three clients. Every read after the artifact exists becomes a Cassandra lookup instead of reaching the model on LiftWing.

Implications
  • Moving off change-prop means moving its controls into the precompute config. For revertrisk-wikidata, change-prop gives us:
    • Filtering. We consume mediawiki.page_change.v1 and match wiki_id: wikidatawiki, page_change_kind: edit|create|move, namespace_id: 0, is_redirect: false, excluding canary.
    • Concurrency. concurrency: 2, capping in-flight requests to the model.
    • Retries. retry_on for 502 and 503.
  • The artifact serves two kinds of consumers. Enterprise and RecentChanges read it directly, and MediaWiki builds the prediction event from it, so the payload has to cover both.
  • Slim events (T433699#12221969). The break is acceptable for us, as downstream users read the prediction from the Data Lake table and can join mediawiki.page_change for the rest. ML team needs to decide on the slim event data model and whether it is a v2 or a new stream.
  • Clients would depend on LAC's read SLO, and ours becomes the lambda's compute latency.
Dependencies
  • ML team — add v2/gRPC to the isvc; define the artifact payload and the slim event data model together; define the lambda SLI
  • Data Persistence SRE — register the artifact; read SLO
  • Data Engineering — the MediaWiki precompute job
  • Wikimedia Enterprise — switch to the LAC endpoint, and tell us what freshness they need after an edit.
Open questions
  • [Data Engineering] does the precompute config provide equivalents for change-prop?
  • [Data Engineering] how long after an edit does the precompute job run?
  • [Data Persistence SRE] if a client read arrives before the precompute finishes, does it trigger a second inference, or wait on the one already in flight?
  • [Data Engineering] if a precompute fails, is it retried? Otherwise the revision produces no prediction event.
Next steps
  • Discuss internally in the ML team first, then follow up with the other teams on the open questions and dependencies.

Event Timeline

isarantopoulos renamed this task from RR-Wikidata: Decide on Linked Artifact Cache for stream (WME consumption via Hoarde) to [draft] RR-Wikidata: Decide on Linked Artifact Cache for stream (WME consumption via Hoarde).Aug 4 2026, 1:04 PM

Just FYI: T403254#12138248

We could also potentially use the LAC response to produce e.g. mediawiki.page_outlink_topic_prediction_change.v1 events here. This may give us a way to eventually decouple LiftWing from change-prop.

Update: internal discussion

The ML team discussed this task in a recent team meeting.

The discussion centred on the possible architectures for attaching the Linked Artifact Cache (Hoarde) to the revert-risk-wikidata prediction stream. More precisely, where the cache sits relative to the rest of the services (e.g., EventGate, LiftWing, etc) and the stream, and what each option implies for how WME consumes predictions.

Our discussion focused on three different architectures which are illustrated in the image below.

Linked Artifact Cache Architecture (6,657×4,572 px, 1 MB)

The three schemas could be considered as three possible options that the ml-team discussed, we are totally open on suggestions/improvements/comments based on the three options. The red blocks in the above schema depict some possible architectural obstacles/disadvantages which were discussed.

The next steps will be to converge into a single architecture and define the necessary pieces that we are missing (if there are any) in order to proceed.

Nice! I think for LAC uses that need to be triggered by edits, we can get you all off of change prop entirely. The business of producing events via eventgate will move into MediaWiki (probably in WikimediaEvents extension?).

All of this is in flux, but: https://wikitech.wikimedia.org/wiki/Prep_Pantry/Architectures#Linked_Artifacts_Cache

Nice! I think for LAC uses that need to be triggered by edits, we can get you all off of change prop entirely. The business of producing events via eventgate will move into MediaWiki (probably in WikimediaEvents extension?).

This would definitely be amazing! I think we could be very happy moving all services to such architecture given that both event consumption and event production are moved outside of LiftWing (so that we don't have to know for which requests we need to produce events - problem with 1st diagram).

All of this is in flux, but: https://wikitech.wikimedia.org/wiki/Prep_Pantry/Architectures#Linked_Artifacts_Cache

This looks quite similar to our 2nd diagram, which looks very promising!

Ya!

we can get you all off of change prop entirely

One flaw I hadn't really thought through before:

Currently, yall consume page_change and just enrich it with prediction details. This is nice because page_change is fat and has a bunch of other event time context (e.g. editor registration_dt, edtior edit_count, etc.) that you don't have in LiftWing.

However, in this "LAC response -> event" flow, we won't have the full page_change event associated with the edit event. What we have is a MW Job that was emitted at the same time the page_change event is emitted.

That Job will fetch a response from LAC, and then cause the e.g. mediawiki.page_*_prediction_change event to be emitted. But all we will have to create that event is MW context at the time the async job is executed and receives the LAC response. We will not be able to fully recreate the same page_change event, e.g. we won't know the editor's edit_count at the time of the edit event.

If these were all brand new streams, we'd create a 'slim' page prediction change data model that doesn't have all that extra fat data, and then emit a slim event with the bare minimum needed.

But, for these existent streams, this is likely a backwards incompatible change.

If we actually do this, we'll have to consider that. We might have to create new stream data products (or v2 versions?) for each of these.

achou renamed this task from [draft] RR-Wikidata: Decide on Linked Artifact Cache for stream (WME consumption via Hoarde) to RevertRisk-Wikidata: move serving and stream to Linked Artifacts Cache.Aug 31 2026, 9:07 AM
achou updated the task description. (Show Details)

Wikimedia Enterprise — switch to the LAC endpoint, and tell us what freshness they need after an edit.

Just noting that in order for this to happen the LAC endpoint would need to be also exposed publicly though the REST Gateway as there is no other way for WME to reach it.

Change #1338218 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[machinelearning/liftwing/inference-services@main] revertrisk_wikidata: Develop KServe v2 and grpc inference protocol

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

Wikimedia Enterprise — switch to the LAC endpoint

Q: I wonder if a better generalized route would be like:

Public LiftWing HTTP API -> LAC -> LiftWing Lambda

And if needed, LiftWing HTTP API could add support for passing Cache-Control: no-cache through to LAC.

Hey @Ottomata, thnx for your comment.

Q: I wonder if a better generalized route would be like:
Public LiftWing HTTP API -> LAC -> LiftWing Lambda
And if needed, LiftWing HTTP API could add support for passing Cache-Control: no-cache through to LAC.

It seems a good idea we can discuss it with the team. I think it is already close to the second schema in: T433699#12211658 (which was the proposed one).

I have already opened a patch for implementing the v2 and grpc support in RR-Wikidara model server in LiftWing as the initial step of this process, I tagged you as a reviewer as well.

I tried to test it locally using a cpu version of the model (running it on Mac). There are detailed instructions on README.md file for reproducing it locally.
I am also pasting here the steps testing end-to-end using cassandra and hoarde:

Requires Docker, Go, curl, plus protoc and grpcurl:

# macOS
brew install protobuf grpcurl
1. Download the model

From the root of inference-services:

mkdir -p ./models/revertrisk/wikidata/20251104121312
curl -L --retry 5 --retry-all-errors \
  -o ./models/revertrisk/wikidata/20251104121312/wikidata_revertrisk_graph2text_v2.pkl \
  https://analytics.wikimedia.org/published/wmf-ml-models/revertrisk/wikidata/20251104121312/wikidata_revertrisk_graph2text_v2.pkl
2. Start revertrisk-wikidata model server

First create the virtualenv:

python3 -m venv .venv
source .venv/bin/activate
pip install -r src/models/revertrisk_wikidata/requirements.txt torch pandas

Then start the server:

MODEL_NAME=revertrisk-wikidata \
MODEL_PATH=$(pwd)/models/... \
CUSTOM_UA="revertrisk-wikidata-local/1.0 (https://phabricator.wikimedia.org/T433699; you@wikimedia.org)" \
PYTHONPATH=.:src/models/revertrisk_wikidata/model_server \
  python3 src/models/revertrisk_wikidata/model_server/model.py
3. Clone hoarde
cd /path/to/repos       # the directory that contains inference-services
git clone https://gitlab.wikimedia.org/repos/sre/hoarde.git
cd hoarde
4. Start Cassandra
docker run -d --name cassandra -p 9042:9042 cassandra:4.1

From the root of hoarde, create the keyspace and the table that hoarde expects:

docker exec cassandra cqlsh -e "
CREATE KEYSPACE IF NOT EXISTS hoarde
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};"

sed "s/{keyspace_name}/hoarde/g; s/{table_name}/revertrisk_wikidata_scores/g" schema.cql \
  | docker exec -i cassandra cqlsh
5. Build hoarde

From the root of hoarde:

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
export PATH="$(go env GOPATH)/bin:$PATH"

make

## Output ##
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# VERSION ......: v1.5.0
# BUILD HOST ...: wmf3620
# BUILD DATE ...: 2026-09-09T13:37:38Z
# GO VERSION ...: go1.24.9
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# go build  -ldflags "-X main.version=v1.5.0 -X main.buildDate=2026-09-09T13:37:38Z -X main.buildHost=wmf3620" -o hoarde .
# go build -o examples/cmd/server/server examples/cmd/server/server.go
# go build -o examples/cmd/client/client examples/cmd/client/client.go
# go build -o cmd/bench/bench            cmd/bench/main.go
# go build -o cmd/inference/client       cmd/inference/client.go
6. Configure hoarde

Create local-config-kserve.yaml at the root of the hoarde repo:

service_name: linked-artifact-cache
log_level: debug

tables:
  revertrisk_wikidata_scores:
    lambda:
      type: kserve_v2
      hostname: localhost
      port: 8081
      model_name: revertrisk-wikidata
      timeout: 120000ms
      content_type: application/json

listen_port: 8181

cassandra:
  keyspace: hoarde
  hosts:
    - localhost:9042
  consistency: one

Start hoarde:

./hoarde -config local-config-kserve.yaml
7. Exercise the cache

The hoarde URL pattern is /revisions/v1/{table}/{wiki}/{page}/{revision}.

Cache miss ("Cache-Control: no-cache"):

curl -s -H "Cache-Control: no-cache" \
  "http://localhost:8181/revisions/v1/revertrisk_wikidata_scores/wikidatawiki/108601362/1892513445"

Expected output:

{"model_name": "revertrisk-wikidata", "model_version": "2", "revision_id": 1892513445,
 "output": {"prediction": false, "probabilities": {"true": 0.10437076243299818, "false": 0.8956292375670019}}}

Cache hit (served from Cassandra observe the Last-Modified header and note that the model
server logs no second request):

curl -i "http://localhost:8181/revisions/v1/revertrisk_wikidata_scores/wikidatawiki/108601362/1892513445"

Expected output:

{"model_name": "revertrisk-wikidata", "model_version": "2", "revision_id": 1892513445, "output": {"prediction": false, "probabilities": {"true": 0.10437076243299818, "false": 0.8956292375670019}}}%

Latest known revision for a page (returns an X-Hoarde-Revision-Id header):

curl -i "http://localhost:8181/revisions/v1/revertrisk_wikidata_scores/wikidatawiki/108601362"

Expected output:

{"model_name": "revertrisk-wikidata", "model_version": "2", "revision_id": 1892513445, "output": {"prediction": false, "probabilities": {"true": 0.10437076243299818, "false": 0.8956292375670019}}}%

Confirm the artifact was persisted:

docker exec cassandra cqlsh -e \
  "SELECT wiki,page,revision,last_modified FROM hoarde.revertrisk_wikidata_scores;"

Expected output:

 wiki         | page      | revision   | last_modified
--------------+-----------+------------+---------------------------------
 wikidatawiki | 108601362 | 1892513445 | 2026-09-09 13:47:10.790000+0000

(1 rows)

8. Tear down

pkill -f "hoarde -config"
pkill -f model_server/model.py          # or: docker compose down
docker stop cassandra && docker rm cassandra

Wikimedia Enterprise — switch to the LAC endpoint

Q: I wonder if a better generalized route would be like:

Public LiftWing HTTP API -> LAC -> LiftWing Lambda

And if needed, LiftWing HTTP API could add support for passing Cache-Control: no-cache through to LAC.

@Ottomata, a quick clarification on "Public LiftWing HTTP API": do you mean the REST Gateway route (api.wikimedia.org/service/lw/inference/...)? The gateway would send revertrisk-wikidata requests to LAC instead of to the inference service, and LAC would call the LiftWing lambda on a miss.

Or do you mean the LiftWing inference service itself calling LAC? We're asking because that second version creates a loop (LiftWing -> LAC -> LiftWing on a cache miss), which we flagged as a problem in diagram 3 of T433699#12211658.

Hm. I was imagining just hiding LAC behind whatever endpoint you expect LiftWing HTTP callers to call.

Where possible, LiftWing inference calls would be via gRPC lambda behind LAC. There'd be no route to the inference endpoint without LAC.

We're asking because that second version creates a loop (LiftWing -> LAC -> LiftWing on a cache miss), which we flagged as a problem in diagram 3 of T433699#12211658.

I'm surely ignorant on details, but is there a problem to go LiftWing hosted HTTP endpoint -> LAC -> LiftWing hosted gRPC lambda endpoint? I wouldn't expect it to matter on which service the front HTTP endpoint lived. It could even be a thin HTTP API router.

Change #1351199 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[integration/config@master] inference-services: Add the revertrisk-wikidata test pipeline

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

Hm. I was imagining just hiding LAC behind whatever endpoint you expect LiftWing HTTP callers to call.
Where possible, LiftWing inference calls would be via gRPC lambda behind LAC. There'd be no route to the inference endpoint without LAC.

Thanks! That makes sense.

I'm surely ignorant on details, but is there a problem to go LiftWing hosted HTTP endpoint -> LAC -> LiftWing hosted gRPC lambda endpoint?

No, as long as the front HTTP endpoint and the gRPC lambda are separate. Our concern in diagram 3 was the model server both calling LAC and serving as LAC's lambda on a cache miss. I think our plan would be to use the REST Gateway as that front endpoint, since that's how LiftWing is already exposed publicly.

Change #1351199 merged by jenkins-bot:

[integration/config@master] inference-services: Add the revertrisk-wikidata test pipeline

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

Change #1338218 merged by jenkins-bot:

[machinelearning/liftwing/inference-services@main] revertrisk_wikidata: Develop KServe v2 and grpc inference protocol

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

Change #1353858 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[operations/deployment-charts@master] ml-services: Deploy latest version of revertrisk-wikidata on staging

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

Change #1353858 merged by jenkins-bot:

[operations/deployment-charts@master] ml-services: Deploy latest version of revertrisk-wikidata on staging

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

Change #1353885 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[operations/deployment-charts@master] ml-services: Add gRPC deployment for revertrisk-wikidata on staging

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

Change #1353885 merged by jenkins-bot:

[operations/deployment-charts@master] ml-services: Add gRPC deployment for revertrisk-wikidata on staging

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

Tested revertrisk-wikidata on ml-staging-codfw from this liftwing-patch and this deployment_patch and grpc_deployment using rev_id 1892513445:

TestResult
v1, rev_id (regression)✅ same prediction as the README
v1, hoarde payload (wiki_id/page_id/revision_id)✅ same prediction
v2 REST, hoarde payload✅ same prediction, wrapped in the v2 envelope
v1, wrong wiki_id✅ 400, error under detail
v2 REST, wrong wiki_id✅ 400, error under detail
v2 REST, empty data✅ 400, error under error
v2 gRPC (via staging gateway), ModelReady✅ ready: True
v2 gRPC, hoarde payload✅ same prediction as REST
v2 gRPC, rev_id✅ same prediction as REST
v2 gRPC, wrong wiki_id⚠️ INTERNAL / "Internal server error" (expected a client error)

The smoke tests can be found in the following files: v1/v2_tests and grpc_tests

There is an issue on grpc request when requesting a wrong 'wiki_id' it returns an InternalError which I found the fix on this outlink patch.

I will make a follow-up patch fixing this and update the comments.

Change #1353935 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[machinelearning/liftwing/inference-services@main] revertrisk_wikidata: Return INVALID_ARGUMENT for client errors on gRPC

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

Hey @Ottomata,

A quick heads-up following our ML meeting: we decided to go with the following schema and proceed with the Hoard integration.

RR-Wikidata LAC Architecture Schema (2,896×994 px, 387 KB)

On ordering, we agreed that calling LiftWing first and then Hoard for caching works fine.

Current status of the RR-Wikidata model server on the LiftWing side: v2/gRPC support is deployed on staging. More details can be found in T433699#12415968 comment.

Thanks! How does change_prop emit the mediawiki.page_revert_risk_wikidata_prediction_change.v1 event?

Also: I'm a little confused about the circular dependency. I understand that LiftWing itself is serving both HTTP and gRPC requests, but aren't those different (and isolated?) endpoints? I would imagine it was like this:

LiftWing HTTP API endpoint 
-> LAC 
-> LiftWing gRPC inference endpoint

Also, FWIW, T436695: Linked Artifact Cache - Automated MediaWiki JobQueue prefetch patches are in progress and I expect them to be merged and put to use by the end of November, if not earlier.

As noted in T433699#12221969, we won't be able to exactly recreate mediawiki.page_revert_risk_wikidata_prediction_change.v1 event stream via this JobQueue based mechanism, but we plan to standardize the emission of LAC based 'derived data computed' events (like revision prediction events) with this.

Not sure what ML's timelines are, but if you can wait a bit, we could possibly avoid change-prop altogether here.

Thanks! How does change_prop emit the mediawiki.page_revert_risk_wikidata_prediction_change.v1 event?

Change-prop doesn't emit it, LiftWing does. Change-prop only consumes mediawiki.page_change.v1, filters it, and POSTs the whole page_change event to the isvc. The model server then builds the event and sends it to EventGate itself:

model.py:601-610: if the request contains the event key, it calls send_event() after predicting.
events.py:219 generate_prediction_classification_event() copies meta, page, revision, etc from the page_change event and adds predicted_classification. The schema is /mediawiki/page/prediction_classification_change/1.3.0.
It posts to EVENTGATE_URL, with the stream name taken from EVENTGATE_STREAM.

Regarding the circular dependency:

Also: I'm a little confused about the circular dependency. I understand that LiftWing itself is serving both HTTP and gRPC requests, but aren't those different (and isolated?) endpoints? I would imagine it was like this:

LiftWing HTTP API endpoint 
-> LAC 
-> LiftWing gRPC inference endpoint

There's no problem as long as the HTTP endpoint and the gRPC are separated endpoints. Do not pay attention to the comment in the picture. We have already discussed it with the ml-team and we chose to go with that schema LiftWing first and then Hoard for caching:

LiftWing HTTP API -> LAC -> LiftWing gRPC lambda

Regarding this:

Also, FWIW, T436695: Linked Artifact Cache - Automated MediaWiki JobQueue prefetch patches are in progress and I expect them to be merged and put to use by the end of November, if not earlier.

As noted in T433699#12221969, we won't be able to exactly recreate mediawiki.page_revert_risk_wikidata_prediction_change.v1 event stream via this JobQueue based mechanism, but we plan to standardize the emission of LAC based 'derived data computed' events (like revision prediction events) with this.

Not sure what ML's timelines are, but if you can wait a bit, we could possibly avoid change-prop altogether here.

I think that this works for us, I will discuss it again with the team. I think we can wait for T436695. Meanwhile we can continue on the Hoarde side: registering the artifact and wiring staging Hoarde to the gRPC lambda (already deployed on ml-staging-codfw). Happy to agree the exact fields and whether it's a v2 or a new stream when all is ready.

Change-prop doesn't emit it, LiftWing does. Change-prop only consumes mediawiki.page_change.v1, filters it, and POSTs the whole page_change event to the isvc. The model server then builds the event and sends it to EventGate itself

Ah, yes, this is what I understood, but the diagram shows "Orchestrator (e.g. Change-prop)" emitting the page_revert_risk_wikidata_prediction_change to eventgate -> kafka.

So, IIUC, if we don't wait for T436695 and do as you have in T433699#12431265, it's

change-prop 
-> LiftWing HTTP 
  [fetch prediction via LAC ->? LiftWing gRPC lambda] 
-> eventgate 
-> ...

Correct? Basically the same as is done today, except the actual prediction value is fetched via LAC?

Ah, yes, this is what I understood, but the diagram shows "Orchestrator (e.g. Change-prop)" emitting the page_revert_risk_wikidata_prediction_change to eventgate -> kafka.

I think the arrows are kinda misleading in the schema. We just mean that the change-prop calls the LiftWing and goes on...

Yes? Basically the same as is done today, except the actual prediction value is fetched via LAC?

Yes, exactly! If we don't wait, the flow would be exactly same as today "plus" the LAC.

That been said, just checking if I have understood correctly, based on T433699#12221969:
When the T436695 is implemented and deployed then LiftWing will not receive any event, it will only receive a gRPC request from Hoarde (wiki_id, page_id, revision_id)?
So will be this the new flow:

  1. User edits Wikidata
  2. MediaWiki does two things at the same moment: a) emits page_change event → Kafka b) queues a background "precompute" job (MW JobQue)
  3. The job runs and calls Hoarde: "give me the prediction for wiki/page/rev"
  4. Hoarde: cache miss → calls LiftWing gRPC lambda with {wiki_id, page_id, revision_id}
  5. LiftWing predicts, returns {model_name, model_version, revision_id, prediction, probabilities}
  6. Hoarde stores it in Cassandra and returns it to the job
  7. The job (MediaWiki) builds the prediction event and sends it → EventGate → Kafka

If the above seems correct then we will probably need to do the following changes:

  1. Turn off the change-prop rule for revertrisk-wikidata.
  2. Remove event production from the isvc and LiftWing code:
    • Drop the event_key branch and send_event() from model.py, plus EVENTGATE_URL/EVENTGATE_STREAM;
    • Remove those env vars from the chart values.
    • We can keep events.py, since other models still use it.
  3. Deprecate the old stream (mediawiki.page_revert_risk_wikidata_prediction_change.v1) together with Data Engineering.

100% correct!

Remove event production

Since this will be a fully new stream, I think we can do this slowly after the new prediction event stream is fully live. I don't know what the uses of mediawiki.page_revert_risk_wikidata_prediction_change.v1 (or other LiftWing emitted streams) are, so it might take us a while to actually decom them. We might want to do so as a larger migration to LAC off of change-prop effort.

Following discussions with the ML team, we've prepared two diagrams of how predictions flow through the Linked Artifacts Cache (LAC): one for event-driven predictions (MediaWiki JobQueue → EventStreams), and one for on-demand requests from users/API clients.
I'm sharing them here so we're all aligned on how we'll move forward.

  1. Event-Streams flow

RR-Wikidata: Event-streams (4,480×2,160 px, 729 KB)

  1. On Demant Flow

rr_wikidata_ondemant_flow_updated (3,823×2,040 px, 615 KB)

Sweeeet! 2 comments:

Event-Streams flow:

  • Just FYI again, the output stream will not be exactly mediawiki.page_revert_risk_wikidata_prediction_change.v1. It will have a slightly different schema and semantics (e.g. it will not have page delete events, etc.). It will likely be named something more like mediawiki.revision_revert_risk_wikidata_prediction_change.v1, and be based on a revision entity. Details about this data modeling conundrum are in T436695#12438085

On Demand flow:

  • "6. on miss: store prediction" looks a little off to me. I think you mean what I expect, let's verify. LiftWing cannot store a prediction in LAC. It can only respond with a result; LAC stores it. I think you are just combining the KServe and gRPC endpoints in the same LiftWing blue box there? It might be more clear if you had two different blue boxes, one for the user facing LiftWing HTTP endpoint, and one for the internal gRPC endpoint.

Change #1353935 merged by jenkins-bot:

[machinelearning/liftwing/inference-services@main] revertrisk_wikidata: Return INVALID_ARGUMENT for client errors on gRPC

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

Change #1358190 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[operations/deployment-charts@master] ml-services: Deploy latest version of revertrisk-wikidata on staging

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

Thank you for your comments @Ottomata !

Event-Streams flow:
Just FYI again, the output stream will not be exactly mediawiki.page_revert_risk_wikidata_prediction_change.v1. It will have a slightly different schema and semantics (e.g. it will not have page delete events, etc.). It will likely be named something more like mediawiki.revision_revert_risk_wikidata_prediction_change.v1, and be based on a revision entity. Details about this data modeling conundrum are in T436695#12438085

We are aware about that, it is fine to have a slimmer stream, it is also mentioned in the description of the current task.
"Slim events (T433699#12221969). The break is acceptable for us, as downstream users read the prediction from the Data Lake table and can join mediawiki.page_change for the rest. ML team needs to decide on the slim event data model and whether it is a v2 or a new stream."

On Demand flow:
"6. on miss: store prediction" looks a little off to me. I think you mean what I expect, let's verify. LiftWing cannot store a prediction in LAC. It can only respond with a result; LAC stores it. I think you are just combining the KServe and gRPC endpoints in the same LiftWing blue box there? It might be more clear if you had two different blue boxes, one for the user facing LiftWing HTTP endpoint, and one for the internal gRPC endpoint.

Yeap you are right. I tried to simplify the schema but it was not clear indeed. I've updated the "on-deamdn-flow-chart" on the comment: T433699#12460775, I think now is more detailed.

Change #1358190 merged by jenkins-bot:

[operations/deployment-charts@master] ml-services: Deploy latest version of revertrisk-wikidata on staging

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

Slim events (T433699#12221969). The break is acceptable for us, as downstream users read the prediction from the Data Lake table and can join mediawiki.page_change for the rest

Ah great! We have to also remember potential public/Cloud Services/Enterprise users?
https://stream.wikimedia.org/?doc#/streams/get_v2_stream_mediawiki_page_revert_risk_wikidata_prediction_change_v1

I've updated the "on-deamdn-flow-chart" on the comment: T433699#12460775, I think now is more detailed.

Perfect! TY!

Follow-up to T433699#12415968, where gRPC requests with a wrong wiki_id returned INTERNAL ("Internal server error" 500) instead of a client error.
Cause: the model server's input checks (invalid wiki_id, invalid rev_id) raised FastAPI's HTTPException(400). That works for REST, but KServe's gRPC server doesn't recognise it and turns it into INTERNAL 500 in the end.
Fix: changes in model server in this patch: 1353935 are deployed on staging. Now the input checks raises KServe's InvalidInput error instead. KServe maps it to the correct status on each protocol, so we avoid InternalServerError 500:

  • REST (v1/v2): HTTP 400, as before but message is under error not detail (results before changes here).
curl -s -w ' %{http_code}\n' $URL/v1/models/revertrisk-wikidata:predict \ 
-H "$HOST" \
-H "Content-Type: application/json" \
-d '{"wiki_id":"enwiki","page_id":1,"revision_id":1892513445}'
{"error":"Invalid wiki_id: enwiki. This model only handles Wikidata edits (wiki_id must be 'wikidatawiki')."} 400
  • gRPC: INVALID_ARGUMENT instead of INTERNAL (results before the changes here). Running the same gRPC test now responds:
ERR {'wiki_id': 'enwiki', 'page_id': 1, 'revision_id': 1892513445} -> StatusCode.INVALID_ARGUMENT Invalid wiki_id: enwiki. This model only handles Wikidata edits (wiki_id must be 'wikidatawiki').

Re-tested on staging:

TestResult
v1/v2 REST, valid payloads✅ same prediction as before
v1/v2 REST, wrong wiki_id✅ 400, message under error
gRPC, ModelReady / hoarde payload / rev_id✅ ready, same prediction
gRPC, wrong wiki_id✅ INVALID_ARGUMENT (was INTERNAL)
gRPC, nonexistent revision✅ INVALID_ARGUMENT, 0.28s
gRPC, 8 fresh revisions (sequential) grpcTest✅ 0.30–0.40s each

Slim events (T433699#12221969). The break is acceptable for us, as downstream users read the prediction from the Data Lake table and can join mediawiki.page_change for the rest

Ah great! We have to also remember potential public/Cloud Services/Enterprise users?
https://stream.wikimedia.org/?doc#/streams/get_v2_stream_mediawiki_page_revert_risk_wikidata_prediction_change_v1

Good point, the task description only mentions/covers the Data Lake users.
Since the new stream will be (probably) a separate stream, we can keep mediawiki.page_revert_risk_wikidata_prediction_change.v1 running in parallel, then announce the new stream, and only decommission the old one after a deprecation period, as you suggested in T433699#12437472. Public consumers who need the page/editor context can still get it from mediawiki.page_change.v1 on EventStreams.
Or, we can make the new stream (slim event) public like we did in this patch:1310570 and give it a "revision-based" name e.g.: mediawiki.revision_revert_risk_wikidata_prediction_change.v1 as you mentioned in T433699#12461684.
Does that sound like a plan?

Yes, sounds great, ty! The announcement and migration period sounds great.

If we plan to do this for other (all?) LiftWing revision predictions, we might want to consider those as part of the announcement and migration plan. That way we can do one announcement and one migration period. This might mean keeping the change-prop triggered events alive longer than we'd like though, so it might depend on ML's timelines and priorities.

Change #1359881 had a related patch set uploaded (by Gkyziridis; author: Gkyziridis):

[machinelearning/liftwing/inference-services@main] revertrisk_wikidata: Integrate LAC (on-deamdn) flow

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

On-demand flow: implemented and tested locally (Lift Wing side)

Following the on-demand flow diagram in T433699#12460775, the user-facing revertrisk-wikidata isvc can now serve predictions through the Linked Artifacts Cache (LAC). Patch: 1359881

How it works

Revision already in Cassandra (hit):

User → revertrisk-wikidata → Hoarde → Cassandra ✔ → back to user

New revision (miss):

User → revertrisk-wikidata → Hoarde → Cassandra ✘ → revertrisk-wikidata-grpc predicts
    → Hoarde stores it in Cassandra → back to user

If LAC fails (error, timeout, connection refused), the isvc logs a warning and predicts locally, so users still get an answer (that prediction will not be stored). LAC_URL must only be set on the user-facing isvc, never on the gRPC lambda.

Testing setup locally
Every box of the diagram runs as its own local process, the same way they are separate services in production. Both model servers run the same code; only LAC_URL differs.

Diagram boxLocalProduction
User / API clientcurlAPI clients via REST Gateway
Lift Wing revertrisk-wikidata (user-facing)model server on :8090 with LAC_URLisvc revertrisk-wikidata
Hoarde (LAC)hoarde on :8181linked-artifacts
CassandraCassandra 4.1 in DockerCassandra
Lift Wing revertrisk-wikidata-grpc (lambda)model server on :8081 (gRPC), no LAC_URLisvc revertrisk-wikidata-grpc

Step 0: Prerequisites

From the root of inference-services, with hoarde cloned and built next to it (see the hoarde section of the model README), and the model downloaded (for more detailed info on downloading the model and installing hoarde check steps 1-6 in T433699#12307634):

ls -la models/revertrisk/wikidata/20251104121312/wikidata_revertrisk_graph2text_v2.pkl   # 662319231 bytes
ls ../hoarde/hoarde ../hoarde/local-config-kserve.yaml

Create the virtualenv for the model server (once):

python3 -m venv .venv
source .venv/bin/activate
pip install -r src/models/revertrisk_wikidata/requirements.txt torch pandas
Step 1: Cassandra

Start Cassandra and wait about a minute until cqlsh answers:

docker run -d --name cassandra -p 9042:9042 cassandra:4.1
# Wait around a minute and then run
docker exec cassandra cqlsh -e "SELECT now() FROM system.local"

#  system.now()
# --------------------------------------
# 1a349dd0-d2dc-11f1-9fc8-15188ebf47e8

Then, from the hoarde repo, create the keyspace and the table hoarde expects (hoarde's own schema.cql):

cd ../hoarde
docker exec cassandra cqlsh -e "CREATE KEYSPACE IF NOT EXISTS hoarde WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};"
sed "s/{keyspace_name}/hoarde/g; s/{table_name}/revertrisk_wikidata_scores/g; s/{comment}/T442542/g" schema.cql | docker exec -i cassandra cqlsh
docker exec cassandra cqlsh -k hoarde -e "DESCRIBE TABLES"
# revertrisk_wikidata_scores
Step 2: Hoarde (terminal 1)

local-config-kserve.yaml has one table, revertrisk_wikidata_scores, whose lambda is on localhost:8081, model_name: revertrisk-wikidata:

cd ../hoarde
./hoarde -config local-config-kserve.yaml

# Check the healthz on another terminal
curl -s -o /dev/null -w '%{http_code}\n' localhost:8181/healthz
# 200

Every miss shows up here as Handling request as a storage miss followed by Calling lambda ... for key {wiki: ..., page: ..., revision: ...}.

Step 3: The lambda, revertrisk-wikidata-grpc (terminal 2)

A model server without LAC_URL. Hoarde calls its gRPC port :8081 on a cache miss:

cd ../inference-services
source .venv/bin/activate
MODEL_NAME=revertrisk-wikidata \
MODEL_PATH=$(pwd)/models/revertrisk/wikidata/20251104121312/wikidata_revertrisk_graph2text_v2.pkl \
CUSTOM_UA="revertrisk-wikidata-local/1.0 (https://phabricator.wikimedia.org/T433699; you@wikimedia.org)" \
PYTHONPATH=.:src/models/revertrisk_wikidata/model_server \
  python3 src/models/revertrisk_wikidata/model_server/model.py

Every call from hoarde shows up here as a grpc method: /inference.GRPCInferenceService/ModelInfer line.

Step 4: The user-facing isvc, revertrisk-wikidata (terminal 3)

The same model server, with LAC_URL pointing at hoarde. It gets its own HTTP port, and no gRPC server (only the lambda serves gRPC). LAC_TABLE matches the local hoarde table name (the default is revertrisk_wikidata, as proposed in T442542):

cd ../inference-services
source .venv/bin/activate
MODEL_NAME=revertrisk-wikidata \
MODEL_PATH=$(pwd)/models/revertrisk/wikidata/20251104121312/wikidata_revertrisk_graph2text_v2.pkl \
CUSTOM_UA="revertrisk-wikidata-local/1.0 (https://phabricator.wikimedia.org/T433699; you@wikimedia.org)" \
LAC_URL=http://localhost:8181 \
LAC_TABLE=revertrisk_wikidata_scores \
PYTHONPATH=.:src/models/revertrisk_wikidata/model_server \
  python3 src/models/revertrisk_wikidata/model_server/model.py --http_port 8090 --enable_grpc false
Step 5: Requests as a user (terminal 4)

Open the last terminal for sending the requests:

LAC=localhost:8090/v1/models/revertrisk-wikidata:predict
CT="Content-Type: application/json"
5.1 Cache miss: the request goes user → isvc → hoarde → lambda
curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 1892513445}'

# Response:
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":1892513445,"output":{"prediction":false,"probabilities":{"true":0.10437076243299818,"false":0.8956292375670019}}} 200

Hoarde (terminal 1) found nothing in Cassandra and called the lambda once, with the page the isvc looked up:

"message":"Handling request as a storage miss"
"message":"Calling lambda {Type:kserve_v2 Hostname:localhost Port:8081 ... ModelName:revertrisk-wikidata ...} for key {wiki: wikidatawiki, page: 108601362, revision: 1892513445}"

The lambda (terminal 2) received exactly one gRPC call:

kserve INFO [interceptors.py:intercept_service():41] grpc method: /inference.GRPCInferenceService/ModelInfer

The user-facing isvc (terminal 3) did not run the model itself: predict_ms: 0.007.

5.2 Cache hit: the same request again
curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 1892513445}'

# Response: 
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":1892513445,"output":{"prediction":false,"probabilities":{"true":0.10437076243299818,"false":0.8956292375670019}}} 200

Same response in 7 ms (terminal 3: kserve.io.v1.models.revertrisk-wikidata:predict: 0.0070). No new Calling lambda line in terminal 1 and no new ModelInfer in terminal 2: it was served from Cassandra.

5.3 The stored artifact
docker exec cassandra cqlsh -e "SELECT wiki,page,revision FROM hoarde.revertrisk_wikidata_scores;"

# wiki         | page      | revision
# --------------+-----------+------------
# wikidatawiki | 108601362 | 1892513445
5.4 A wrong page_id cannot poison the cache

LAC stores artifacts under the page in the URL, so the isvc never trusts the caller's page. Here the caller sends page_id: 1:

curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"wiki_id":"wikidatawiki","page_id":1,"revision_id":1892513445}'

# Response
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":1892513445,"output":{"prediction":false,"probabilities":{"true":0.10437076243299818,"false":0.8956292375670019}}} 200

docker exec cassandra cqlsh -e "SELECT * FROM hoarde.revertrisk_wikidata_scores WHERE wiki='wikidatawiki' AND page=1;"

# wiki | page | revision | content | last_modified | metadata
# ------+------+----------+---------+---------------+----------
# (0 rows)

It was a cache hit under the real page 108601362 (6 ms, no lambda call), and nothing was stored under page 1.

5.5 Client errors return 400 and never reach LAC
curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 999999999999}'

# Response:
# {"error":"Invalid rev_id: 999999999999. The revision does not exist."} 400

curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"wiki_id":"enwiki","page_id":1,"revision_id":1892513445}'

# Response:
# {"error":"Invalid wiki_id: enwiki. This model only handles Wikidata edits (wiki_id must be 'wikidatawiki')."} 400

curl -s -w ' %{http_code}\n' localhost:8090/v2/models/revertrisk-wikidata/infer -H "$CT" \
  -d '{"inputs":[{"name":"input","shape":[1],"datatype":"BYTES","data":["{\"rev_id\": 1892513445}"]}]}'

# Response:
# {"error":"This endpoint serves predictions through the Linked Artifacts Cache and only accepts KServe v1 requests."} 400

The nonexistent revision is caught by the MW API page lookup, before LAC (which would otherwise turn any lambda error into a 500, see T438201).

5.6 A fresh revision: a real cold miss, then a hit

Pick the latest Wikidata edit:

curl -s -A "rrwd-local-test (https://phabricator.wikimedia.org/T433699)" \
  "https://www.wikidata.org/w/api.php?action=query&list=recentchanges&rcnamespace=0&rctype=edit&rcprop=ids&rclimit=1&format=json"

# Response:
# {"batchcomplete":"","continue":{...},"query":{"recentchanges":[{"type":"edit","pageid":27059141,"revid":2561662632,"old_revid":2277521012,"rcid":2642257289}]}}

Send it twice:

curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 2561662632}'
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":2561662632,"output":{"prediction":false,"probabilities":{"true":0.40872234847287026,"false":0.5912776515271297}}} 200
curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 2561662632}'
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":2561662632,"output":{"prediction":false,"probabilities":{"true":0.40872234847287026,"false":0.5912776515271297}}} 200
  • First request: a miss in 1.6s. Hoarde called the lambda for page: 27059141, revision: 2561662632, the same page the MW API reports. The lambda spent ~1.2s on MW API calls and ~0.2s on the model (preprocess_ms: 1175, predict_ms: 198).
  • Second request: a hit in 6 ms, no lambda call.
docker exec cassandra cqlsh -e "SELECT wiki,page,revision FROM hoarde.revertrisk_wikidata_scores;"
#  wiki         | page      | revision
# --------------+-----------+------------
#  wikidatawiki | 108601362 | 1892513445
#  wikidatawiki |  27059141 | 2561662632
5.7 LAC down: fall back to a local prediction

Stop hoarde (Ctrl+C in terminal 1) and repeat the request:

curl -s -w ' %{http_code}\n' $LAC -H "$CT" -d '{"rev_id": 2561662632}'
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":2561662632,"output":{"prediction":false,"probabilities":{"true":0.40872234847287026,"false":0.5912776515271297}}} 200

The user gets the same answer. The isvc (terminal 3) logged the failure and ran the model itself (predict_ms: 446):

WARNING:root:LAC request to http://localhost:8181/revisions/v1/revertrisk_wikidata_scores/wikidatawiki/27059141/2561662632 failed: ClientConnectorError(... Connect call failed ... 8181)
WARNING:root:Falling back to a local prediction for rev_id 2561662632.
5.8 Without LAC_URL the behaviour is unchanged

A direct request to the lambda's HTTP port, i.e. the isvc as it runs today:

curl -s -w ' %{http_code}\n' localhost:8080/v1/models/revertrisk-wikidata:predict -H "$CT" -d '{"rev_id": 2561662632}'
# {"model_name":"revertrisk-wikidata","model_version":"2","revision_id":2561662632,"output":{"prediction":false,"probabilities":{"true":0.40872234847287026,"false":0.5912776515271297}}} 200

The same prediction as the one stored in LAC.

Step 6: Tear down
pkill -f "hoarde -config"
pkill -f model_server/model.py
docker stop cassandra && docker rm cassandra

Summary

CaseResult
Cache miss✅ one lambda call, prediction stored under the correct page
Cache hit✅ same prediction in 6-7 ms, no lambda call
Wrong page_id✅ served from the real page, nothing stored under the wrong one
Nonexistent revision / wrong wiki / v2✅ 400, LAC not called
Fresh revision✅ cold miss 1.6s, then 6 ms
LAC down✅ same prediction, computed locally
No LAC_URL✅ unchanged behaviour

Visible changes for users

  • Revisions already in LAC are answered in milliseconds; a new revision adds one MW API lookup and the LAC hop.
  • A nonexistent revision now returns 400 instead of 500.

Next steps (on-demand flow)

  • Once the revertrisk_wikidata table exists on staging (T442542): We will set LAC_URL on the staging revertrisk-wikidata isvc and we can test end-to-end (on staging).
  • After testing on staging move everything on prod in the same way.

If LAC fails (error, timeout, connection refused), the isvc logs a warning and predicts locally, so users still get an answer (that prediction will not be stored).

Fancy!

gkyziridis changed the task status from Open to In Progress.Thu, Oct 29, 11:18 AM