Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Wikipedia Path turns French Wikipedia into a graph of links, then finds the shortest chain of clicks from one article to another.

Every article is a node. Every link from one article to another is an edge. With this graph, you can answer questions like “how many clicks from Tour Eiffel to Pikachu?”:

$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"
Searched 99,483 pages in 30 ms.
2 clicks from 'Tour Eiffel' to 'Pikachu':
  0. Tour Eiffel
  1. Jeu vidéo
  2. Pikachu

What is in the repository

PathContent
WikipediaPath.GraphBuilder/Command-line tool: downloads the dumps, builds the graph, reads it
WikipediaPath.GraphBuilder.Tests/xUnit tests
docs/This book, and the WGRF file format specification
flake.nixNix dev shell, package and local MariaDB scripts

How it works, in short

  1. download fetches the SQL dumps of French Wikipedia and a list of date and country pages from Wikidata.
  2. decompress unpacks the .gz files.
  3. provision loads the SQL dumps into a local MariaDB database.
  4. build reads the database and writes one binary file, graph.wgrf.
  5. info, explore and path read that file.

The graph file uses the WGRF format. It is a compact, memory-mapped layout built for fast breadth-first search. The specification describes it byte by byte.

Size of the data

Numbers from the frwiki dump of 2026-09-01:

ItemSize
Articles (nodes)2,777,420
Links (edges)235,141,317
Searchable names (titles and redirects)4,619,033
Compressed dumps (.gz)about 2.7 GB
Decompressed SQLabout 12.5 GB
MariaDB data directoryabout 64 GB
graph.wgrfabout 1.1 GB

Limitations

  • Only French Wikipedia (frwiki) is tested. The --wiki option exists, but the date and country examples in the spec are French.
  • The clickstream covers one month and the dumps another, so some measured links are missing from the graph and their clicks are dropped.
  • Wikidata categories come from a live query, so they can be newer than the dump.

License

Wikipedia Path is licensed under the GNU Affero General Public License v3.0 only (AGPL-3.0-only). See the LICENSE file at the root of the repository.

Local env

Requirements

  • Linux, x86-64 or ARM64.
  • Nix with flakes enabled. The dev shell brings everything else: the .NET 10 SDK, MariaDB, clang (for the native AOT build), perf, the .NET profiling tools and mdbook.
  • About 80 GB of free disk for the dumps and the database (see Size of the data).
  • About 8 GB of RAM for the MariaDB buffer pool. You can change this, see Local database.

Enter the dev shell

nix develop

The shell sets WPATH_DB_DIR to .mariadb/ at the root of the repository and MYSQL_UNIX_PORT to the socket inside it. Every command that talks to MariaDB uses these values by default.

Build a graph from scratch

Run these commands from the root of the repository. By default, every file goes into dumps/.

db-start                                             # start the local MariaDB
dotnet run --project WikipediaPath.GraphBuilder -- download
dotnet run --project WikipediaPath.GraphBuilder -- decompress
dotnet run --project WikipediaPath.GraphBuilder -- provision   # takes hours
dotnet run --project WikipediaPath.GraphBuilder -- build

The result is dumps/graph.wgrf. The pipeline page explains each step.

You can also build the native binary once and call it directly:

nix build
./result/bin/WikipediaPath.GraphBuilder --help

Or run it without a checkout:

nix run . -- --help

Use the graph

dotnet run --project WikipediaPath.GraphBuilder -- info
dotnet run --project WikipediaPath.GraphBuilder -- path "Tour Eiffel" "Pikachu"
dotnet run --project WikipediaPath.GraphBuilder -- explore "Pikachu" --max-depth 1

These commands only need the .wgrf file. They don’t need MariaDB.

Read this book locally

mdbook serve docs --open

The build pipeline

Building a graph takes four commands. Each one reads the output of the one before.

dumps.wikimedia.org ──download──▶ dumps/*.gz ──decompress──▶ dumps/*.sql
Wikidata query service ──download──▶ dumps/frwiki-wikidata-categories.tsv

dumps/*.sql ──provision──▶ MariaDB tables
MariaDB tables + categories .tsv + clickstream .tsv ──build──▶ dumps/graph.wgrf

1. download

Fetches, from a Wikimedia dumps mirror:

FileUsed for
frwiki-<date>-page.sql.gzTitles, namespaces, which pages are redirects
frwiki-<date>-redirect.sql.gzWhere each redirect points
frwiki-<date>-linktarget.sql.gzLink targets, by title
frwiki-<date>-pagelinks.sql.gzLinks, from a page to a link target
frwiki-<date>-page_props.sql.gzThe Wikidata item of each article
clickstream-frwiki-<month>.tsv.gzHow often readers follow each link

With --date latest (the default), it picks the newest dump run where all five tables are finished.

It then asks the Wikidata Query Service which items are dates or countries, and writes frwiki-wikidata-categories.tsv. See download.

2. decompress

Unpacks every .gz file in the directory, several files at once. See decompress.

3. provision

Loads every .sql file into MariaDB with the mariadb client. Each table is dropped and created again. This is the slow step: pagelinks alone is about 9 GB of SQL. See provision.

4. build

Reads five tables from MariaDB, the categories file and the clickstream when there is one, then writes graph.wgrf. The database is only read, never changed. See build.

Safe to stop and run again

Every step writes to a temporary name first (.part or .tmp) and renames the file only when it is complete. A file under its final name is always complete.

  • download skips files that are already there with the right size, and resumes a .part file with an HTTP range request.
  • decompress skips files that are already decompressed.
  • download does not query Wikidata again if the categories file exists. Delete it to refresh.

provision is the exception: it starts each table over.

Local database

The builder does not parse SQL dumps itself. It loads them into a local MariaDB server, then queries the tables. The dev shell provides the server and three scripts to manage it.

Scripts

ScriptWhat it does
db-startCreates the data directory on first run, starts the server, creates the wikipedia database
db-stopStops the server
db-resetStops the server, deletes all data, starts a fresh server

Open a SQL shell with:

mariadb wikipedia

Where the data lives

  • Data directory: $WPATH_DB_DIR/data, which is .mariadb/data in the repository.
  • Socket: $WPATH_DB_DIR/mariadb.sock. The server does not listen on TCP.
  • Log: $WPATH_DB_DIR/mariadb.log.

.mariadb/ is in .gitignore.

Settings

The server is tuned for bulk loading of data you can download again. It gives up durability for speed: no binary log, no doublewrite buffer, and the log is not flushed on each commit. If the machine crashes during provision, run provision again.

VariableDefaultEffect
WPATH_DB_BUFFER_POOL8GInnoDB buffer pool size
WPATH_DB_NAMEwikipediaDatabase created by db-start and used by provision and build

Set them before db-start, for example WPATH_DB_BUFFER_POOL=16G db-start. The buffer pool size applies each time the server starts.

Be careful with db-reset

db-reset deletes every loaded table. Loading them again with provision takes hours. Only run it when you really want an empty database.

Read-only access from build

build never writes to the database. Each query runs in a session opened with SET SESSION TRANSACTION READ ONLY, and the builder checks @@session.transaction_read_only before it reads any row. If the check fails, the build stops.

From Wikipedia to a graph

This page explains, in plain words, how build turns Wikipedia tables into nodes and edges. The exact rules are in the “Builder responsibilities” part of the WGRF specification.

Nodes are articles

A node is a page of the main namespace (page_namespace = 0) that is not a redirect. Talk pages, user pages, categories and templates are not in the graph.

Nodes are numbered from 0, in the order of their Wikipedia page_id. The graph keeps the page_id of each node in the page_id column, so you can go back to Wikipedia.

Titles are stored as Wikipedia shows them, with spaces: Tour_Eiffel becomes Tour Eiffel.

Redirects are names, not nodes

A redirect such as Paris (France) is not a node. The builder follows it to the real article and:

  • adds its title as an extra searchable name (an alias) for that article,
  • rewrites every link to the redirect so that it points to the article.

The builder follows chains of redirects up to 8 steps. It drops a redirect that loops, is longer, points to a missing page, to another namespace or to another wiki. Links to a dropped redirect are dropped too.

The pagelinks table says “page A links to link target T”. The linktarget table gives the title of T. The builder resolves that title to a node, through redirects if needed.

A link becomes an edge only when both ends are articles in the graph. Then, for each article:

  • targets are sorted by node id,
  • duplicates are removed (two links can reach one article through different redirects),
  • a link from an article to itself is removed.

Red links (links to pages that don’t exist) are dropped.

Categories come from Wikidata

Some pages are hubs that connect almost everything: dates (14 juillet, 1913, XIXe siècle) and countries (France). They make paths short but not interesting. To let you skip them, each node has one category byte.

The category comes from the Wikidata item of the article:

  1. download asks the Wikidata Query Service for all items that are an “instance of” a day, a date, a month, a year, a decade, a century, a millennium, a “year in topic” page or a country, and that have an article on French Wikipedia.
  2. build reads the page_props table to find the Wikidata item of each article, and looks it up in that list.

The spec has the full list of values and the Wikidata classes behind each one.

path and explore use this column with --exclude-date-page and --exclude-country.

Clicks come from the clickstream

Wikimedia publishes a monthly clickstream: how many times readers went from one page to another. When build finds a clickstream file, it gives each edge the number of clicks measured on it, in the click_count column.

  • Only rows of type link count. Rows from search engines, other sites or the search box don’t.
  • Both titles resolve like links do, through redirects. Clicks that land on the same edge through different redirects add up.
  • A row whose link is not in the graph is dropped. The clickstream month and the dump date differ, so a link can have been added or removed in between.
  • The clickstream leaves out pairs with fewer than 10 clicks in the month. Most edges have no count at all: that means “not measured”, not “never clicked”.

Each node also gets a view_count: the sum of every clickstream row that ends on the page, whatever the referer (another article, a search engine, another site, none). It is close to the page’s views for the month, a little lower because of the missing small pairs.

path and explore use both columns, see Path search. They count a missing value as 0.

What the graph looks like

Output of info on the 2026-09-01 dump:

Degrees            mean   median      p99          max        zero
  out-links        84.7       40      612        5,374         254 dead ends
  in-links         84.7       14      862      570,854      46,002 orphans
  reciprocal edges: 112,781,200 (48.0 %), linked both ways
  • A typical article links to about 40 others.
  • A few pages get a huge number of links: France has more than 550,000 incoming links.
  • 46,002 articles have no incoming link: you can’t reach them by clicking.
  • 254 articles have no outgoing link: a path can end there, but not go through them.

Path search

path finds a chain of links between two articles. --strategy picks what “best” means:

StrategyFindsSearch
followedThe links readers click most (default)Followed paths
shortestThe fewest clicks, all links counting the sameBidirectional BFS
popularA way through pages readers click into mostPage costs
nicheA way through pages few others link toPage costs
niche-clicksA way through pages readers rarely click intoPage costs
niche-viewsA way through pages readers rarely visitPage costs

followed, popular, niche-clicks and niche-views read the click_count and view_count columns. A link or a page without a count counts 0. On a graph built without a clickstream, every count is 0: followed then returns a path with the fewest clicks, and the command warns you. strategies prints how each one scores a path.

A plain breadth-first search (BFS) starts from the first page and visits its links, then the links of those links, and so on. With about 85 links per page, the number of pages grows very fast at each level.

path searches from both ends at once:

  • The forward side starts at the source page and follows links forward.
  • The backward side starts at the goal page and follows links backward: “which pages link to this one?”

At each step, the search grows one whole level of one side. It stops as soon as a page is reached by both sides. Because each side is complete up to its depth, that page closes a shortest path.

Each side keeps, for each page it reached, the page it came from. The path is rebuilt by walking these links back from the meeting page to both ends.

The backward side without a reverse index

A WGRF file stores only outgoing links. To find “pages that link to X”, you need a reverse index, and the format does not have one yet (see “Open / deferred” in the spec). Building one when the file loads takes several seconds.

Instead, a backward step scans every link in the graph once, in parallel, and keeps the links that point into the backward frontier. This costs the same whatever the frontier size: about 235 million links read in order.

A forward step reads only the links of the frontier pages, but in random order.

So the search picks the side to grow by cost:

  • If the forward frontier has fewer than 5 links per node in the graph (about 14 million links for French Wikipedia), it takes a forward step.
  • Otherwise, it takes a backward step with a full scan.

For example, Tour Eiffel to Pikachu visits about 100,000 pages and takes about 30 ms.

Parallel levels with stable results

explore and the forward steps of path expand a level in parallel. Several threads can reach the same new page at the same time. To keep the result the same on every run, each new page keeps the parent with the lowest position in the frontier, as a single-threaded search would. The output does not depend on thread timing.

Followed paths

path --strategy followed looks for the path readers are most likely to click through, from the clickstream.

A link’s cost is about how unlikely its click is, in bits. It compares the link’s clicks with the clicks on all the links of its page:

cost = 1 + bits(clicks out of the page) - bits(clicks on the link)
Share of the page’s clicksCost
more than half1
about a quarter2 or 3
about a thousandth11
no clicks33

A link without clicks costs 33, more than any clicked link. So the search takes a long chain of clicked links before one unclicked link. The counts are shares of each page’s own clicks: a link that gets most of the clicks of a small page costs as little as the main link of a big one.

Dijkstra with buckets

The cost belongs to the link, so a page can be reached again later at a lower cost. The search is Dijkstra’s algorithm: it fixes a page’s distance only when it takes the page out of the queue. Costs are integers from 1 to 33, so the queue is one bucket per distance (Dial’s algorithm).

The search runs forward only, on one thread, and takes pages in the order they entered their bucket, so the result is the same on every run. The clicks out of each page come from one parallel scan when the command starts.

Page costs

popular, niche, niche-clicks and niche-views put the cost on the page you enter instead of on the link. They differ by what they count for each page and whether a high count is cheap or expensive.

StrategyCountCheap pages
popularclicks on links into the pagehigh counts
nichelinks into the pagelow counts
niche-clicksclicks on links into the pagelow counts
niche-viewsthe page’s view_countlow counts

The in-link and click counts come from one parallel scan of every link when the command starts, about 100 ms on French Wikipedia.

Niche: cost from rarity

The niche strategies make entering a page cost the number of bits of its count, at least 1:

CountCost
0 or 11
2 to 32
4 to 73
1,024 to 2,04711
about 100,00017

Every page costs at least 1, so a path does not get long just to use small pages: three pages with 10 in-links (cost 4 each, 12 in total) lose to one page with 1,000 (cost 10). Doubling a page’s count adds 1 to its cost, so a hub costs about as much as a few obscure pages.

popular turns this around. A page with the most-clicked count costs 1, and each bit less adds 1:

cost = 1 + bits(largest count in the graph) - bits(count of the page)

A page nobody clicked into costs the most, 1 plus the bits of the largest count. As with the niche strategies, a short path through less popular pages can still beat a long detour through popular ones.

The goal and the total

The search returns a path with the lowest total cost over the pages after the source. The goal’s own cost is the same for every path, so it changes nothing.

Search by cost buckets

This is a shortest-path search with a cost on each page instead of on each link: every way into a page costs the same. So the search can grow pages by increasing distance and fix a page’s distance the first time it reaches it. Any later way in comes from a page at least as far.

Costs are small integers (1 to 33), so pages wait in one bucket per distance instead of a priority queue. The search takes the lowest non-empty bucket, expands it in parallel like one level of a breadth-first search, and puts each new page into the bucket for its distance plus its cost. It stops when it reaches the goal. When several paths share the lowest cost, the result is the same on every run, for the same reason as a breadth-first level.

The search goes forward only. A backward side would need a full scan of every link for each bucket, and there are dozens of buckets. For example, niche from Tour Eiffel to Pikachu visits about 180,000 pages and takes about 40 ms after the in-link count.

Explore with the clickstream

explore walks level by level like a breadth-first search, so each page shows at its shortest distance from the start. --strategy picks which page of the level above becomes its parent:

  • followed (default): the page whose link to it readers click most. Ties, and pages with no clicked link from the level above, keep the first-found parent.
  • first-found: the first page that reached it, see Parallel levels.

With a clickstream, each page shows the clicks of the link from its parent. --order clicks (default) lists the most clicked links first.

Adding a strategy

Each strategy is one PathStrategy object listed in PathStrategies.All. path --strategy, its help, the missing-column warnings and the strategies command all read that list, so PathCommand has no per-strategy code.

The code lives in WikipediaPath.GraphBuilder/Analyze/Paths/:

FolderContents
Paths/The path and strategies commands
Strategies/PathStrategy, IPathSearch, PageCostStrategy, each strategy and the PathStrategies list
Algorithms/The searches (PathSearch, FollowedPathSearch, PageCostPathSearch), PathResult and PageCounts

A strategy picks an algorithm and the counts it scores with. An algorithm knows nothing about strategies or the command line.

A strategy defines:

MemberRole
NameThe --strategy value, lowercase with dashes
SummaryOne line for path --help: what the path goes through
DetailsA few sentences for strategies: how it scores, what each page shows
Readsclick_count, view_count or none. path warns when the graph lacks one
PrepareCounts what the search needs once, and returns an IPathSearch

IPathSearch.Find runs the search. IPathSearch.Score returns the text printed next to each page of the result, or null.

Pick the shape that fits:

  • A cost per page from one count. Add a PageCostStrategy entry. It takes a function that returns one count per node (PageCounts has in-links, clicks in, clicks out and views), whether low or high counts are cheap, and the unit printed after each count. It reuses the page costs search, and needs no new class.
  • Another cost or another search. Subclass PathStrategy and return your own IPathSearch. ShortestStrategy and FollowedStrategy are the examples.

Then add the new name to the tables above and in the command reference. The tests check that every strategy has a unique name, a summary and details.

Excluded pages

With --exclude-date-page or --exclude-country, the search never goes through a page of that kind. The source and the goal can still be one. This works with every strategy, and with explore.

Development

Run everything inside nix develop.

Build and test

dotnet build
dotnet test

The tests use xUnit v3 on Microsoft.Testing.Platform (set in global.json). They don’t need MariaDB or a real dump: they write small WGRF files to a temporary directory.

The test folders mirror the source folders: the tests of Analyze/Paths/Algorithms/PathSearch.cs are in Analyze/Paths/Algorithms/PathSearchTests.cs. Shared helpers live in Support/: TestGraph writes WGRF files to a temporary directory, and SampleGraphs holds the small graphs that several test files use.

WikipediaPath.GraphBuilder.Tests/Support/WgrfFile.cs is a small WGRF reader written from the spec only, separate from WgrfReader. Writer tests use it, so a bug shared by the writer and the reader still fails a test.

Formatting

Before you commit, check the formatting:

dotnet format --verify-no-changes

Run dotnet format to fix the files.

Warnings

Both projects set TreatWarningsAsErrors. The tool is published with native AOT (PublishAot), so avoid code that needs runtime reflection. JSON goes through source-generated contexts, like DumpStatusJsonContext.

NuGet dependencies and Nix

Nix builds offline, so it needs a lock of every NuGet package: deps.json. After you add or update a package, regenerate it:

nix run .#update-deps

Native build

nix build            # result/bin/WikipediaPath.GraphBuilder

Or without Nix:

dotnet publish WikipediaPath.GraphBuilder -c Release -r linux-x64 -o out

Running the build output outside the dev shell

A dotnet build output needs to find the .NET runtime. Outside the dev shell, set DOTNET_ROOT:

export DOTNET_ROOT=$(dirname "$(readlink -f "$(which dotnet)")")

The AOT binary from nix build does not need it.

Profiling

The dev shell has dotnet-trace, dotnet-counters and perf:

dotnet tool run dotnet-counters monitor -n WikipediaPath.GraphBuilder
dotnet tool run dotnet-trace collect -- ./result/bin/WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"

build --verbose also prints rates, ETA and memory use every few seconds.

Changing the file format

docs/src/spec/wgrf.spec.md is the source of truth. Code that reads or writes WGRF follows it exactly. If you change the format, change the spec in the same commit, and bump the version when old files can no longer be read.

Documentation

This book lives in docs/. Preview it with:

mdbook serve docs --open

mdbook build docs writes the HTML to docs/book/, which is ignored by git.

WikipediaPath.GraphBuilder

WikipediaPath.GraphBuilder is the command-line tool of the repository. It builds the WGRF graph from Wikipedia dumps, then reads it.

WikipediaPath.GraphBuilder <command> [options]
CommandWhat it does
downloadFetches the dumps, the clickstream and Wikidata categories
decompressUnpacks the .gz files
provisionLoads the .sql dumps into MariaDB
buildReads MariaDB and writes the .wgrf graph
infoSummarizes a graph and checks it against the spec
exploreShows the pages reachable from one page
pathFinds a path between two pages: most followed, shortest, popular or niche
strategiesDescribes each path strategy

Every command has --help.

download

Downloads the Wikipedia table dumps, the clickstream and the Wikidata categories.

WikipediaPath.GraphBuilder download [options]
OptionDefaultDescription
-o, --outputdumpsDirectory for the files
--wikifrwikiWiki database name
--datelatestDump run as yyyyMMdd, or latest
--clickstreamlatestMonth as yyyy-MM, latest, or none to skip it
--mirrorhttps://dumps.wikimedia.org/Base URL of a Wikimedia dumps mirror

Choosing the dump

With --date latest, the command lists the dump runs on the mirror, newest first, and reads each run’s dumpstatus.json. It picks the first run where these jobs are done: pagetable, pagelinkstable, linktargettable, redirecttable and pagepropstable.

With an explicit date, the command fails if one of these jobs is not finished.

Downloading

  • Files download one at a time. Wikimedia limits parallel connections per IP.
  • Each file goes to <name>.part, then moves to <name> once its size and SHA-1 match what dumpstatus.json says.
  • An interrupted .part file resumes with an HTTP range request.
  • Network errors retry up to 5 times, with a longer wait each time.
  • A file already present with the right size is skipped.

Wikidata categories

After the dumps, the command runs one SPARQL query per category on the Wikidata Query Service and writes <wiki>-wikidata-categories.tsv:

# Wikidata categories of frwiki articles, queried 2026-09-30T22:25:29Z from https://query.wikidata.org/sparql
Q2151	day
Q2150	day
...
Q750	country
Q16	country

If the file exists, the command does not query again. Delete it to get fresh data.

This data is from the day you run the command, not from the dump date.

decompress

Decompresses every .gz file in a directory.

WikipediaPath.GraphBuilder decompress [options]
OptionDefaultDescription
-i, --inputdumpsDirectory with the .gz files
-o, --outputsame as --inputDirectory for the decompressed files
-j, --parallelismnumber of CPU coresFiles decompressed at the same time

Gzip decoding can’t be split inside one file, so the work is split by file. The largest files start first, so the longest job does not start last. With the default dump set, pagelinks takes most of the time.

Each file is written to <name>.part, then renamed. A file that already exists is skipped. If an archive is corrupt, its .part file is deleted and the command fails.

The .gz files are kept. Delete them yourself if you need the disk space.

provision

Loads the .sql dumps into MariaDB. Each dump drops its table and creates it again.

WikipediaPath.GraphBuilder provision [options]
OptionDefaultDescription
-i, --inputdumpsDirectory with the .sql files
-d, --database$WPATH_DB_NAME, else wikipediaTarget database. It must exist
--socket$MYSQL_UNIX_PORTMariaDB unix socket
--clientmariadbMariaDB command-line client
--keep-row-formatoffKeep ROW_FORMAT=COMPRESSED from the dumps
-j, --parallelism4Tables loaded at the same time

Start the server first with db-start. See Local database.

How it loads

The command starts one mariadb client per file and streams the file to it. The client parses the SQL. Progress shows every 10 seconds.

Only files ending in .sql are loaded. The clickstream .tsv is ignored.

Row format

Wikimedia dumps create tables with ROW_FORMAT=COMPRESSED. Compressed pages cost CPU on every insert, and loading is about twice as slow. By default, the command removes this option from the CREATE TABLE statements. The tables then use more disk.

Use --keep-row-format if disk space matters more than time.

Time

This step takes hours: the pagelinks dump alone is about 9 GB of SQL. Don’t run it again unless you have new dumps.

build

Reads the provisioned tables and writes a WGRF graph file.

WikipediaPath.GraphBuilder build [options]
OptionDefaultDescription
-o, --outputdumps/graph.wgrfFile to write
-d, --database$WPATH_DB_NAME, else wikipediaDatabase with the tables
--socket$MYSQL_UNIX_PORTMariaDB unix socket
--clientmariadbMariaDB command-line client
--categoriesdumps/frwiki-wikidata-categories.tsvCategories file from download
--clickstreamnewest dumps/clickstream-frwiki-*.tsvDecompressed clickstream for the click_count and view_count columns
-v, --verboseoffProgress every few seconds, queries, memory, what was dropped

What it needs

  • The tables page, redirect, linktarget, pagelinks and page_props. The command stops if one is missing.
  • The categories file. The command stops if it is missing.
  • Optionally, a decompressed clickstream .tsv. Without --clickstream, the command takes the newest clickstream-frwiki-*.tsv in dumps/. If there is none, the graph has no click_count and view_count columns. If you give --clickstream and the file is missing, the command stops.

Steps

  1. Read every main-namespace page from page.
  2. Read redirects from redirect, then resolve each one to an article.
  3. Read page_props to give each article its Wikidata category.
  4. Read the clickstream, if any: every row adds to the views of the page it ends on, and each link row with both titles resolved to articles gives clicks to that pair.
  5. Read linktarget to map each link target to an article.
  6. Read pagelinks in primary key order. Rows come grouped by source page, which is node order, so each node’s edges go straight to the file. The edge list is never held in memory.
  7. Write titles, the title index, the click counts and the directories.

From Wikipedia to a graph explains the rules applied in each step.

Output

The file is written to <output>.tmp, then renamed. If the build fails, the .tmp file is deleted and the old graph stays in place.

The command never writes to the database. See Read-only access from build.

Querying MariaDB

The builder runs each query through the mariadb client with --batch --quick and parses the tab-separated output. It does not use a .NET database driver.

info

Prints a summary of a WGRF file and checks that it follows the spec.

WikipediaPath.GraphBuilder info [options]
OptionDefaultDescription
-i, --inputdumps/graph.wgrfFile to read
--top10Entries in the “most links” and “most clicked” rankings

Output

  • Header: version, build date, file size, node, edge and name counts.
  • Sections and columns: id, name, offset and size of each region.
  • Degrees: mean, median, 99th percentile and maximum of outgoing and incoming links, dead ends and orphans, and how many links go both ways.
  • Titles: number of aliases, mean and longest title.
  • Categories: articles per Wikidata category.
  • Clickstream: edges with clicks, total clicks and total views, when the file has them.
  • Rankings: pages with the most outgoing and incoming links, the most viewed pages and the most clicked links.
  • Checks: errors and warnings.

Checks

The command reads the whole file (about 15 seconds for French Wikipedia).

  • An error means the file breaks the spec, for example an edge that points past the last node. The command exits with code 1.
  • A warning means the file breaks a builder rule, for example unsorted or duplicate edges, or self-loops. The command still exits with 0.

When everything is fine, it prints:

Checks (14.6 s)
  ok: the file follows the spec and the builder rules.

explore

Shows the pages you can reach from one page, level by level.

WikipediaPath.GraphBuilder explore [title] [options]
OptionDefaultDescription
titlePage to start from
-i, --inputdumps/graph.wgrfFile to read
--nodeStart from this node id instead of a title
-d, --max-depth2Clicks away from the start page, 0 to 32
-n, --max-children10Pages shown under each page. The rest are counted
--orderClicksOrder of child pages: Clicks (most clicked link first), Links (most links first), Title or Id
-s, --strategyfollowedParent of each page: followed (most clicked link from the level above) or first-found
-f, --formattreetree for text, dot for Graphviz
--exclude-date-pageoffNever walk into a date page
--exclude-countryoffNever walk into a country page

Example

$ WikipediaPath.GraphBuilder explore Pikachu -d 2 -n 3
Pikachu (node 502244, page_id 1797391)
  depth 0:            1 new,            1 reached (0.00 % of the graph)
  depth 1:          458 new,          459 reached (0.02 % of the graph)
  depth 2:       31,309 new,       31,768 reached (1.14 % of the graph)

Pikachu  (458 links, 458 new)
├── Pichu et ses évolutions  (104 clicks, 339 links, 7 new)
│   ├── Yōkai  (0 clicks, 238 links)
│   ├── Raijū  (0 clicks, 164 links)
│   ├── Kami (divinité)  (0 clicks, 160 links)
│   └── … 4 more
├── Liste des Pokémon  (53 clicks, 193 links, 2 new)
│   ├── Système de gestion d'exceptions  (0 clicks, 72 links)
│   └── Dolman  (0 clicks, 12 links)
├── Pokémon  (45 clicks, 351 links, 84 new)
│   ├── Histoire du jeu vidéo  (41 clicks, 498 links)
│   ├── Jeu vidéo de rôle  (38 clicks, 220 links)
│   ├── Éponymie  (36 clicks, 250 links)
│   └── … 81 more
└── … 455 more

The tree is a shortest-path tree: each page shows once, at its shortest distance from the start. With --strategy followed, a page sits under the page of the level above whose link to it readers click most, and “clicks” is the count of that link. A page no link from the level above was clicked into keeps the first page that reached it, with 0 clicks. --strategy first-found always keeps the first page, as a plain breadth-first search. On a graph without a clickstream, both give the same tree and the labels show no clicks. See Explore with the clickstream.

In Graphviz output, each edge is labeled with its clicks.

Graphviz output

WikipediaPath.GraphBuilder explore Pikachu -d 2 -n 5 -f dot | dot -Tsvg > pikachu.svg

Graphviz is not in the dev shell. Install it yourself if you need it.

The start title follows the same rules as path, see Title matching.

path

Finds a chain of links from one page to another: the one readers follow most, the shortest, or one through popular or little-known pages.

WikipediaPath.GraphBuilder path <from> <to> [options]
OptionDefaultDescription
fromPage to start from
toPage to reach
-i, --inputdumps/graph.wgrfFile to read
-s, --strategyfollowedfollowed, shortest, popular, niche, niche-clicks or niche-views, see below
--exclude-date-pageoffNever go through a date page (day, year, century, …)
--exclude-countryoffNever go through a country page

Strategies

StrategyFindsEach page shows
followedThe links readers click mostclicks on the link to it
shortestThe fewest clicksnothing
popularA way through pages readers click into mostclicks on links into it
nicheA way through pages few others link toin-links
niche-clicksA way through pages readers rarely click intoclicks on links into it
niche-viewsA way through pages readers rarely visitviews

All strategies except shortest and niche need a graph built with a clickstream. Without one, every count is 0 and the command warns you. Run strategies for how each one scores a path, and see Path search for the search algorithms.

The path goes to standard output. The search statistics and messages go to standard error.

The command exits with 1 when a title is unknown or when no path exists.

When several best paths exist, the command prints one of them. It is the same one on every run.

Examples

On the 2026-09-01 dump with the 2026-08 clickstream:

$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu"
Prepared 'followed' in 123 ms.
Searched 181,402 pages in 286 ms.
5 clicks from 'Tour Eiffel' to 'Pikachu':
  0. Tour Eiffel
  1. Tour métallique de Fourvière  (17 clicks on this link)
  2. Téléphone mobile  (16 clicks on this link)
  3. Smartphone  (121 clicks on this link)
  4. Jeu vidéo  (11 clicks on this link)
  5. Pikachu  (23 clicks on this link)

$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu" -s shortest
Prepared 'shortest' in 0 ms.
Searched 99,483 pages in 30 ms.
2 clicks from 'Tour Eiffel' to 'Pikachu':
  0. Tour Eiffel
  1. Jeu vidéo
  2. Pikachu

$ WikipediaPath.GraphBuilder path "Tour Eiffel" "Pikachu" -s niche
Prepared 'niche' in 98 ms.
Searched 178,161 pages in 45 ms.
3 clicks from 'Tour Eiffel' to 'Pikachu':
  0. Tour Eiffel  (2,083 in-links)
  1. Légende urbaine  (483 in-links)
  2. Thème de Lavanville  (12 in-links)
  3. Pikachu  (392 in-links)

followed takes 5 clicks here because nobody clicked Tour Eiffel → Jeu vidéo that month: an unclicked link costs more than a chain of clicked ones.

niche-clicks and niche-views count a page without clickstream data as 0, the rarest value. They tend to go through pages the clickstream never measured, such as 1944 en sport.

Title matching

The command tries, in this order:

  1. The text as you typed it.
  2. With underscores replaced by spaces (Tour_Eiffel).
  3. With a capital first letter (tour Eiffel).
  4. Ignoring case, if every match is the same page.

Redirect names work too. The command tells you when it follows one:

'Paris (France)' redirects to 'Paris'.

If nothing matches, it suggests the closest names.

Excluding pages

--exclude-date-page and --exclude-country need the category column. Graphs built by the current build always have it. The two pages you give can still be a date or a country.

See Path search for how the search works.

strategies

Describes each path --strategy: what the path goes through, the columns it reads, how it scores a path and what each printed page shows. It reads no graph.

WikipediaPath.GraphBuilder strategies [name]
OptionDefaultDescription
nameStrategy to describe. All of them without it
$ WikipediaPath.GraphBuilder strategies niche
niche: through pages few others link to.
  Reads: links.
  Entering a page costs the bit length of its number of in-links, at least 1: 1 for 0 or 1 in-link,
  11 for 1,024 to 2,047. The path has the lowest total cost over the pages after the start. Each
  page shows its in-links.

The texts come from the strategy definitions in Analyze/Paths/Strategies/PathStrategies.cs, the same ones path --help summarizes.

Specification

This part holds the formal specification of the files the project writes.

  • WGRF file format: the binary graph file written by build and read by info, explore and path.

The specification is the source of truth. When the code and the spec disagree, the code is wrong, or the spec must change in the same commit.

Reading the WGRF spec

  • Layout, Header, Section directory, Column directory, Node / Title / ByTitle, Alignment describe the bytes. You need these to write your own reader.
  • Builder responsibilities describe what goes into the file: which pages become nodes, how redirects and links are handled, where categories come from. The From Wikipedia to a graph page explains the same rules in plain words.
  • Open / deferred lists what is not decided yet. Don’t implement these parts until the spec defines them.

WGRF — Wikipedia-fr Path Graph Binary Format

Status: draft · Version: 1

Read-only, mmap-friendly CSR graph of Wikipedia-fr articles for BFS / shortest-path.


Conventions

  • Little-endian. uint16/uint32/uint64 = 2/4/8 bytes. Strings are UTF-8, not terminated.
  • All offsets are byte offsets from the start of the file.
  • Every section and column starts aligned to its element size; the builder pads before it.

Model

Two levels of self-describing tables:

  • Section directory — locates the top-level regions (nodes, titles, columns, …). A reader finds every region through this table, never by a hard-coded position.
  • Column directory — one section that lists the per-edge / per-node columns. An edge is not a struct but an index: edge i is target_id[i], flags[i], … across parallel columns. Both tables carry byte_length, so a reader skips any section or column it doesn’t recognize — new data is added without a version bump. Adjacency is CSR: Node[i] marks where node i’s out-edges start; the sentinel Node[node_count] closes the last node.

Layout

[Header]                       // 64 bytes, fixed
[Section * section_count]      // section directory
[Column  * column_count]       // one section: the column directory
[Node    * (node_count + 1)]   // CSR row offsets, id-indexed, + sentinel
[<column data blocks>]         // target_id (mandatory) + optional columns, any order
[Title   * (node_count + 1)]   // id-indexed, + sentinel
[TitleBytes]                   // packed UTF-8, padded to 4
[ByTitle * by_title_count]     // alphabetical search index (canonical + aliases)

Physical order is illustrative; only the directories are authoritative.


Header — 64 bytes

struct Header {
    byte[4] magic;              // "WGRF"
    uint32  version;            // 1
    uint64  build_date;         // Unix seconds, UTC
 
    uint32  node_count;
    uint32  reserved0;
    uint64  edge_count;         // length of edge-domain columns
 
    uint16  section_count;
    uint16  reserved1;
    uint32  reserved2;
    uint64  sections_offset;    // -> Section[section_count]
 
    byte[16] reserved;
};

A reader rejects a file whose magic is not WGRF or whose version it does not know: a new version means existing readers would misread the file. sections_offset is 8-aligned.

Section directory

struct Section {                // 24 bytes
    uint16 section_id;          // see registry
    uint16 reserved;
    uint32 element_size;        // bytes/element; 0 if variable (e.g. title_bytes)
    uint64 offset;              // start of the section
    uint64 byte_length;         // total size — enables skipping unknown sections
};

Registry (gaps left for growth):

idnameelement_sizenotes
0columns32the column directory (see below)
1nodes4Node[node_count + 1]
2titles4Title[node_count + 1]
3title_bytes0packed UTF-8
4by_title12ByTitle[by_title_count]

Sections columns, nodes, titles, title_bytes, by_title are all required in v1; future sections may be optional. count is derived: byte_length / element_size, except the sentinel arrays which hold node_count + 1.

Column directory (section 0)

struct Column {                 // 32 bytes
    uint16 column_id;           // see registry
    uint8  domain;              // 0 = edge-indexed, 1 = node-indexed
    uint8  encoding;            // 0 = dense fixed-width
                                // 1 = sparse pairs (index:uint32, value:uint32)
                                // 2 = delta+varint            (reserved)
    uint8  element_size;        // bytes/element for dense; 8 (one pair) for sparse;
                                // 0 if variable
    uint8  reserved8;
    uint16 reserved16;
    uint64 offset;
    uint64 byte_length;         // enables skipping unknown columns
    uint64 count;               // element count (dense) or pair count (sparse)
};

Registry:

idnamedomainencodingnotes
0target_idedgedense u32mandatory — hot BFS array, stored alone
1flagsedgedense u8per-edge bits, meaning TBD
2click_countedgesparseclicks from the clickstream; optional
16page_idnodedense u32Wikipedia curid; optional
17categorynodedense u8kind of page, see below; optional
18view_countnodedense u32visits from the clickstream; optional

A reader that cannot find column_id = 0 MUST reject the file. Others are optional. Because click_count is sparse, an absent edge means “no clickstream data” — no flag needed to tell that apart from a measured zero.

Sparse columns

A sparse column (encoding = 1) stores only the elements that have a value, as pairs:

struct SparsePair {             // 8 bytes
    uint32 index;               // edge or node index, per the column's domain
    uint32 value;
};
  • element_size is 8, count is the number of pairs and byte_length is count * 8.
  • Pairs are sorted by strictly ascending index: no index appears twice. A reader finds one element by binary search. A node’s edges are contiguous, so the pairs of its edges form one contiguous run.
  • index is below edge_count for an edge-domain column, below node_count for a node-domain one. Like first_edge, it assumes edge indices fit in 2^32.
  • An index without a pair has no value. That is not the same as a value of 0.

click_count values

Number of times readers followed the link of this edge during one month, from the Wikipedia clickstream. One file uses one month. Only edges the clickstream measured have a pair, so most edges have none. When the column is absent, the file was built without clickstream data.

view_count values

Number of times readers reached the page during the same month, from any referer: another article, a search engine, another site or no referer. It sums every clickstream row that ends on the page. The clickstream leaves out the rarest pairs, so this is a lower bound of the page views, not an exact count. When the column is absent, the file was built without clickstream data.

category values

One byte per node naming what kind of page it is. A page has at most one category.

valuenameexample
0noneany page not listed below
1day14 juillet
2date10 mai 1981
3monthJanvier
4month_of_yearJanvier 1913
5year1913, 44 av. J.-C.
6decadeAnnées 1910
7centuryXIXe siècle
8millenniumIIe millénaire
9year_in_topic1913 en sport
10countryFrance, Écosse

Values 1 to 8 are date pages. year_in_topic is a chronology of one field for one period, not a date page. country covers historical states, empires and constituent countries too, so République démocratique allemande is one. Values 11 to 255 are reserved: a reader treats them as none. When the column is absent, no page has a known category; that is not the same as every page being none.

Node / Title / ByTitle

struct Node   { uint32 first_edge;     }; // index into edge-domain columns
struct Title  { uint32 first_byte;     }; // offset into title_bytes
struct ByTitle {                          // 12 B, sorted alphabetically by name
    uint32 name_first_byte;               // -> title_bytes
    uint32 name_length;
    uint32 node_id;                       // canonical node this name resolves to
};
  • out_degree(i) = Node[i+1].first_edge - Node[i].first_edge.
  • Title length of node i = Title[i+1].first_byte - Title[i].first_byte.
  • by_title_count >= node_count (canonical titles + searchable redirect aliases; many entries may share one node_id). Name→id is a binary search comparing against title_bytes. Title stays id-ordered for the id→name direction used during traversal.
  • “Alphabetically” means ordinal comparison of the UTF-8 bytes (no case folding, no collation), shorter name first when one is a prefix of the other; equal names are ordered by node_id.
  • Alias names live in title_bytes after the canonical titles, past Title[node_count], so the Title sentinel still closes the last canonical title.
  • uint32 widths on first_edge / first_byte assume the arrays fit in 2^32; confirm from dump statistics.

Alignment

Header is 64 (8-aligned). Because every region has an explicit offset, the builder pads before each so it starts aligned to its element: Section table → 8, Column table → 8, nodes → 4, each dense column → its element_size, each sparse column → 4, titles → 4, title_bytes → padded to 4 before by_title, by_title → 4. What precedes a region never affects its alignment.

Padding bytes and every reserved* field are zero. A section’s or column’s byte_length covers its data only, never the padding after it.

Builder responsibilities (not in the file)

  • Nodes: main-namespace (page_namespace = 0) pages that are not redirects. Node ids follow ascending page_id.

  • Titles: stored in their displayed form: the underscores of page_title become spaces (Tour_Eiffel → Tour Eiffel). Aliases use the same form.

  • Redirects: resolve each to its canonical target, rewrite edges to canonical ids, drop redirects as nodes — the file holds only real articles. Optionally append a redirect’s title to title_bytes and add a ByTitle entry pointing at the canonical id. The v1 builder adds an alias for every resolved redirect. It follows redirect chains up to 8 hops. A redirect that loops, runs longer, points at a missing page, at another namespace or at another wiki (rd_interwiki) is dropped: no alias, and links to it are dropped like red links.

  • Edges: a link becomes an edge when both ends resolve to a node. Each node’s targets are sorted by ascending node id, without duplicates (two links can resolve to one article through redirects) and without self-loops.

  • page_id: if the page_id column is present, the page_id→node_id lookup is built at load. The v1 builder always writes it.

  • category: taken from Wikidata. The article’s item comes from page_props (pp_propname = 'wikibase_item'), and its category from the item’s “instance of” (P31) statements, matched directly, without following “subclass of” (P279):

    categorythe item is an instance of
    dayQ14795564 (point in time with respect to recurrent timeframe) and is part of (P361) an instance of Q47018901 (calendar month)
    dateQ47150325 (calendar day of a given year)
    monthQ47018901 (calendar month)
    month_of_yearQ47018478 (calendar month of a given year)
    yearQ3186692 (calendar year), Q577 (year) or Q29964144 (year BC)
    decadeQ39911 (decade)
    centuryQ578 (century)
    millenniumQ36507 (millennium)
    year_in_topicQ18340514 (events in a specific year or time period)
    countryQ6256 (country), Q3624078 (sovereign state), Q3024240 (historical country), Q48349 (empire) or Q1520223 (constituent country)

    An item that matches several rows gets the smallest value. Redirects keep no category of their own. Wikidata is queried live, so its statements can be newer than the dump. The v1 builder always writes the column.

  • click_count: taken from a monthly clickstream file (clickstream-<wiki>-<yyyy-MM>.tsv, rows of prev, curr, type, n). Only rows of type = link count. prev and curr are resolved like link targets: by title, through redirects, to a node. A row whose titles don’t both resolve, or whose two nodes have no edge between them in the file, is dropped. Rows that resolve to the same edge (through different redirects) add up, capped at 2^32 - 1. The clickstream month can differ from the dump date, so some rows name links the dump no longer has. The v1 builder writes the column when a clickstream file is available, and leaves it out otherwise.

  • view_count: taken from the same clickstream file as click_count. Every row counts, whatever its type. curr is resolved like a link target; a row whose curr doesn’t resolve is dropped. Rows that resolve to the same node add up, capped at 2^32 - 1. The v1 builder writes the column exactly when it writes click_count.

Open / deferred

  • Reverse (bidirectional) index — not in the file; additive as a new section + columns.
  • uint32 field widths (first_edge, first_byte) pending dump statistics.
  • Edge compression (encoding = 2, delta+varint on target_id) — reserved, unspecified.
  • flags bit meanings — TBD.