Repository navigation
Closing the Loop
Previous Chapter: Feeding Spiders
- Introduction
- Harvesting seeds from the items
- Cross seeding
- One writer per slot
- Writing without blocking the consumer
- A seed runs once
- Branch seeds and leaf seeds
The previous chapter covered how the crawl manager reads seeds from the frontier and feeds the spiders with them. This chapter covers the other half of the loop: how the new seeds discovered by the spiders get back into the frontier. That is the job of the consumer, the first issuer of the post-crawl processing chain (see Issuers). Besides passing the items to the next stage, it harvests from them the new seeds, and writes them into the frontier slots.
crawl manager ──► spider jobs ──► items ──► consumer ──► items to the next stage
▲ │
└──────────── frontier ◄─────────────────┘
new seeds
The spiders don't write seeds anywhere: they just put them in their items. In our example, every article item has
its tags and authors, and every one of them is potentially a new seed. The spider declares in its
seeds_fields attribute which fields carry seeds (see
The spider side: receiving seeds).
The consumer collects the seeds while it processes the items of a job, and writes them into the frontier once per
job, in the post_process_input_items() hook:
import logging
from collections import defaultdict
from hcf_backend.manager import HCFManager
from shub_workflow.issuer import IssuerScriptWithSCJobInput, IssuerItem, ItemId
from myproject.utils import get_slotname
LOGGER = logging.getLogger(__name__)
SEEDS_FIELDS = ("tags", "authors") # all the fields that any spider may declare in seeds_fields
class Article(IssuerItem):
url: str
title: str
tags: list
authors: list
class Consumer(IssuerScriptWithSCJobInput[Article]):
loop_mode = 120
output_folder = "gs://mybucket/consumer"
parallel_outputs = 10
source_crawlmanagers = ("py:crawlmanager.py",)
def __init__(self):
super().__init__()
self.hcf = HCFManager(self.project_settings["FRONTIER_NAME"], project_id=self.project_id)
self.job_seeds = defaultdict(set)
def build_item_id(self, item: Article) -> ItemId:
return ItemId(f"{item['source']}:{item['url']}")
def process_item(self, item: Article, input_source):
for field in SEEDS_FIELDS:
self.job_seeds[field].update(item.get(field) or [])
super().process_item(item, input_source)
def post_process_input_items(self, spider_job, args):
_, _, canonical_name, spidercls = args
for field in spidercls.seeds_fields:
if seeds := self.job_seeds.get(field):
slot = get_slotname(canonical_name, field)
for seed in seeds:
self.hcf.add_request(slot, {"fp": seed, "qdata": {}})
self.hcf.flush(slot)
LOGGER.info(f"Wrote {len(seeds)} seeds into slot {slot}.")
self.job_seeds.clear()The consumer is started with a target that matches all the spiders whose seeds it handles, for example
class:MySiteBaseSpider. Writing the seeds of a job in the per job hook, before the job is tagged as consumed, keeps
the at-least-once
guarantee: if the consumer stops in the middle of a job, the job is not consumed yet, and the next instance will
read it, and write its seeds, again. Writing them twice is harmless, because the frontier discards the fingerprints
it has already seen.
There is no need to deduplicate the seeds before writing them, beyond the set used to collect them: the frontier does it.
Notice that the slot where a seed is written depends on the kind of seed (the field), not on the spider that found it. The tags spider finds articles with authors, so it feeds the authors slot, which is read by the authors spider. And the authors spider finds articles with tags, so it feeds the tags slot:
mysite.com_tags slot ──► tags spider ──── tags ────► mysite.com_tags slot
└──── authors ─► mysite.com_authors slot
mysite.com_authors slot ──► authors spider ──── authors ──► mysite.com_authors slot
└──── tags ─────► mysite.com_tags slot
This is why the spiders declare separately seeds_source, the kind of seeds they read, and seeds_fields, the kinds
of seeds they produce. Each spider explores the site in its own way, and the seeds discovered by each one feed all
the others. A spider that doesn't produce some kind of seed simply doesn't list it in its seeds_fields.
Only one process may write to a frontier slot at a time (see The Hubstorage Crawl Frontier). The simplest way to guarantee it is a single consumer for all the spiders that write into the frontier. A single consumer can serve dozens of sources, and it should be the first option.
When a single consumer cannot keep up, there are two ways of splitting the work without breaking the rule:
-
One consumer per source. Each consumer instance reads the jobs of a single source (target
canonical:<name>) and writes only into the slots of that source. As the slots are per source, the writers never overlap. -
Split slots. When a single source is too big for one consumer, its slot can be split into N slots
(
mysite.com_tags,mysite.com_tags_1, ...,mysite.com_tags_<N-1>). Then N consumer instances split the jobs of that source among them (for example, by the job number modulo N), each one writing only into its own split slot. The crawl manager reads from all the split slots, in turn: the ready-made seeds crawl manager does it with itsSLOT_SPLITSattribute.
Each additional consumer instance of a split also produces its own output batches, which is no problem: the downstream stages are partitioned by item id, not by consumer.
Watch out for the operations by hand, too: adding or moving seeds with the frontier tool into a slot is writing, so do it while the consumer that writes that slot is stopped.
Writing into the frontier is slow compared with the processing of items, and a consumer that handles many sources can spend most of its time waiting for the frontier. A common optimization is a background writer thread per slot: the consumer puts the seeds of each job into the queue of the slot writer and continues with the next job, while the writer thread adds and flushes them. As each slot has a single writer thread, the single writer rule still holds.
This optimization trades some seeds for a consumer that never stalls:
- The queue of each writer is bounded, and when it is full, the consumer drops the seeds of that job and moves on. It does not block on a full queue. A blocking put slows the consumer down to the pace of the frontier: when the spiders produce many jobs with large seed sets (a big source, or a backlog after a stop), the consumer spends long periods waiting to write seeds and reads no new jobs in the meantime. The backlog of finished jobs then grows without end, and with it the delay of every item of every source down the whole data chain. The consumer's job is to keep the items flowing, and seeds only feed future crawling. A consumer that writes synchronously, as above, has the same problem at that scale: that is the point at which you move to background writers.
- The drops are visible: they are counted in a stat, so the loss can be measured instead of guessed.
- The job is tagged as consumed when its items are written, possibly before its seeds are flushed into the frontier. If the consumer stops at that moment, the seeds still in the queue are lost too. Don't try to close this gap by delaying the consumed tag until the seeds are flushed: that ties the consumer to the frontier again.
- On close, the consumer writes the queued seeds before finishing. But if it crashes, it must fail right away: a writer thread that keeps the process alive after the main loop died leaves a job that outputs nothing until ScrapyCloud cancels it as stalled, hiding the error that killed it.
shub-workflow implements this as the mixin HCFSeedsWriterMixin, in
shub_workflow/utils/hcf.py
(it requires the optional hcf-backend package). Add it to the consumer, and replace the synchronous writes by
write_seeds() (the self.hcf manager of the consumer is no longer needed):
from shub_workflow.issuer import IssuerScriptWithSCJobInput
from shub_workflow.utils.hcf import HCFSeedsWriterMixin
class MyConsumer(HCFSeedsWriterMixin, IssuerScriptWithSCJobInput[MyItem]):
frontier_name = "myfrontier" # if not set, read from the project setting FRONTIER_NAME
...
def post_process_input_items(self, spider_job, args):
_, _, canonical_name, spidercls = args
for field in spidercls.seeds_fields:
if seeds := self.job_seeds.get(field):
self.write_seeds(get_slotname(canonical_name, field), list(seeds)) # never blocks
self.job_seeds.clear()| Attribute | Default | Meaning |
|---|---|---|
frontier_name |
None |
The frontier. If not set, read from the project setting FRONTIER_NAME. |
seeds_queue_size |
20 |
Max seed lists queued for writing in each slot. When full, new seeds are dropped. |
seeds_write_chunk_size |
100 |
The writer flushes into the frontier each this number of seeds. |
seeds_writers_stop_timeout |
1800 |
Max seconds to wait on close for each slot writer to write its queued seeds. |
The writers report the stats seeds/enqueued/<slot>, seeds/dropped/<slot> and seeds/written/<slot> (seeds sent
to the frontier, which may still discard the already seen ones). The writer threads are daemons, so a crash of the
consumer ends the job right away as failed, with its traceback, losing only the queued seeds. A writer thread that
dies on an error is restarted with the next seeds of its slot.
Start with the simple synchronous version above, and move to the mixin only when the frontier writes are proven to be the bottleneck.
The fingerprint memory of the frontier has a strong consequence on the behavior of the crawl: each seed runs only once per slot. A tag that was already crawled is discarded when it is found again, even if the listing of that tag has new articles since then. The crawl expands while new seeds are discovered, and the slots slowly drain. When a slot is empty, its crawl manager has nothing more to do: the crawl of that source is complete.
To crawl again the same seeds — for example, to find the articles published since the previous crawl — the slot
must be reset: deleted, and bootstrapped again. This can be done by hand, with the frontier tool
(--delete-slot) and a seed job (see
Bootstrapping a crawl),
or automatically: a crawl manager that finds its slot empty can delete it and schedule a seed job by itself.
Resetting a slot recrawls everything in it, so the automatic reset is usually conditioned on the rest of the workflow
needing more data (for example, when the downstream queues are low), as described in
Keeping It Running.
Seeds that must be crawled again with a regular period, independently of the frontier, are better handled outside it: by a spider that runs periodically with a fixed list of seeds, or a periodic sweep of the whole site.
So far, all our seeds were branch seeds: tags and authors lead to listings, from where the spiders extract the articles and discover more seeds. The spiders extract the items from the listings themselves.
Sometimes the listings don't contain all the data, and every item must be extracted from its own page. Then the work can be split between two spiders: a discovery spider crawls the listings from the branch seeds, and yields, besides new branch seeds, the ids of the items found (the leaf seeds). An extraction spider receives leaf seeds and extracts each item from its page:
branch slots ──► discovery spider ──► branch seeds ──► branch slots
└──► item ids ──────► leaf slot ──► extraction spider ──► items
Both spiders are fed by crawl managers in the same way, and the consumer writes the leaf seeds exactly as the
branch ones: they are just another seeds field (for example, item_ids) of the discovery spider. Only the reading
side changes: the extraction spider has item_ids as its seeds_source, and it doesn't produce seeds itself.
The leaf slot has an interesting property: thanks to the fingerprint memory, it is also the record of all the items ever discovered. An item id that was already extracted is discarded when the discovery spider finds it again in another listing. So, unlike the branch slots, a leaf slot is usually never reset: resetting it would extract again every item ever found. Recrawling the branch slots then finds only the items that are new.
Next Chapter: The Post-Crawl Data Chain
Foundations
Building blocks
Designing workflows at scale
- Managing Hubstorage Crawl Frontiers
- Independent Agents and Role Separation
- Feeding Spiders
- Closing the Loop
- The Post-Crawl Data Chain
- Keeping It Running
- Reference Architectures
Operating workflows