STATIYA_POLUCHATEL_1
SP-05 · URL DISCOVERY CRAWLER
P2 / CRAWL CORE / EXECUTE THE PLAN, DON'T INVENT IT

URL discovery crawler

Crawler исполняет уже утверждённый preflight-план. Его задача — надёжно и воспроизводимо перечислить кандидатов на статьи, не уходя за пределы ресурса, не создавая дублей и не теряя прогресс при ошибках или перезапуске.

10pipeline stages
15acceptance checks
8Luna bounded blocks
HTTPdefault path

01 / Граница ответственности

Crawler ≠ article classifier.

SP-05 отвечает за discovery/fetch/queue/resume. Он не решает окончательно, что является статьёй. Он передаёт кандидатов в SP-06 вместе с evidence о том, откуда URL был найден и как был получен.

Нельзя расширять scope молча.

Если crawler видит новый домен, новую ветку URL или неожиданную структуру, которая не описана crawl_plan, он логирует это и пропускает/ставит review condition. Он не начинает исследовать новый интернет сам.

02 / Канонический pipeline

01
LOAD PLAN

Read immutable crawl_plan snapshot for this run.

02
SEED

Create initial request set from approved sitemap/feed/archive/listing nodes.

03
NORMALIZE

Canonicalize request URL for request-level dedup only.

04
SCOPE CHECK

Reject external/private/disallowed hosts or paths.

05
QUEUE

Persist request with source, parent, depth, discovery method and priority.

06
FETCH

HTTP-first fetch with timeout/retry/rate policy.

07
PARSE LINKS

Extract only links relevant to approved traversal nodes/patterns.

08
EMIT CANDIDATE

Pass likely content pages to candidate store/classifier input.

09
CHECKPOINT

Persist queue/visited/counters so restart is safe.

10
TERMINATE

Stop when approved traversal graph is exhausted or explicit blocker fires.

03 / Request record

FieldMeaning
request_idStable crawl-request identity for this run.
job_idOwning job.
source_idOwning source/dataset.
url_originalURL as discovered.
url_normalizedRequest-dedup normalized URL.
parent_request_idDiscovery parent, if any.
discovery_methodsitemap / feed / archive / category / pagination / page-link / browser.
surface_idcrawl_plan node that authorized this request.
depthTraversal depth relative to source seed.
priorityDeterministic queue priority.
statusPENDING / FETCHING / FETCHED / SKIPPED / FAILED / BLOCKED.
http_statusFinal HTTP status if fetched.
content_typeResponse content type.
redirect_chain[]Observed redirects.
final_urlFinal fetched URL after redirects.
fetched_atTimestamp.
retry_countRetries already used.
error_codeNormalized failure code.
error_detailShort diagnostic text, safe for logs.
candidate_emittedWhether sent to article candidate layer.
checkpoint_versionJob state version that includes this request.

04 / URL normalization

IDRuleContract
N-01Scheme/host casingLowercase scheme and hostname.
N-02FragmentsDrop URL fragment for request identity.
N-03Default portsNormalize :80/:443 where equivalent.
N-04Dot segmentsResolve path dot-segments safely.
N-05Trailing slashDo not globally collapse slash/non-slash unless source-specific redirect/canonical evidence proves equivalence.
N-06Query paramsDo not strip all query parameters. Remove only source-proven tracking/session params; preserve pagination/content parameters.
N-07Percent encodingNormalize only safe equivalent forms; avoid changing path semantics.
N-08Canonical tagDo not use canonical tag as request identity before fetch; store it later for logical-article dedup.
N-09RedirectsFinal redirected URL may become preferred request target for future duplicates, but historical request evidence remains.
N-10TitlesNever dedupe URLs by page title.
Request dedup ≠ logical article dedup.

SP-05 предотвращает повторную загрузку одного и того же request URL. Решение, что два разных URL ведут на один логический материал, относится к SP-07 и использует canonical/redirect evidence.

05 / Scope guard

IDRuleRequired behavior
S-01Allowed hostsOnly hosts explicitly approved by crawl_plan may be fetched.
S-02SubdomainsNot automatically included. Must be approved or verified canonical variant.
S-03External linksIgnore by default; they are not source corpus.
S-04Private/local targetsReject via SSRF/private network checks; detailed implementation belongs to SP-13.
S-05SchemesAllow http/https only for crawler requests.
S-06File typesSkip obvious non-HTML corpus assets: images, video, archives, binaries, fonts, stylesheets.
S-07Utility endpointsSkip logout/login/cart/account/search unless explicitly part of source traversal plan.
S-08Calendar trapsBound date/archive traversal to discovered evidence; do not generate infinite dates.
S-09Pagination loopsVisited normalized listing URLs + repeated-content/page signature stop conditions.
S-10Generated URLsCrawler may follow discovered URLs, not invent combinatorial parameter spaces.

06 / Fetch policy

AreaPolicy
HTTP firstUse normal HTTP client/crawler path for all pages by default.
Browser fallbackAllowed only for surface/page class proven to require JS rendering.
TimeoutBound connect/read/overall timeout; no request can block worker indefinitely.
RetriesSmall bounded retries only for transient network/5xx/429 classes.
4xxMost 4xx are terminal except source-specific retryable cases.
429Respect Retry-After where present; reduce rate rather than hammering.
5xxRetry with bounded exponential backoff, then mark FAILED.
RedirectsBound redirect count; reject redirect to disallowed host.
Content typeParse HTML/XML/feed only as appropriate; do not feed binaries to parser.
Body sizeSet safe max response size; very large responses need explicit handling.
TLSVerify TLS normally; do not disable certificate verification to make crawl 'work'.
CompressionAllow standard gzip/br but count decompressed size for limits.
Browser fallback measured, not magical.

Каждый переход в Playwright/browser path должен иметь trigger reason и отдельный log event. Доля browser requests должна быть видна в run summary.

07 / Queue priority and traversal

PriorityClassWhy
P0robots/sitemap topologyNeeded to understand and enumerate source structure.
P1approved archive/category/listing pagesPrimary traversal surfaces.
P2candidate article pagesContent candidates discovered from authoritative surfaces.
P3secondary pagination/listing expansionsContinue known traversal.
P4fallback page-link discoveryOnly if crawl_plan allows it.
QUEUE INVARIANTS - one job owns one source - one normalized request identity per job - enqueue is idempotent - discovery_method and surface_id are always known - queue state persists - in-flight crash may retry safely - no request can create arbitrary new host scope - queue exhaustion is a valid, observable source-exhaustion signal

08 / Structured crawler events

EventMinimum payload
CRAWL_STARTjob_id, plan_id, source_id, seed_count
REQUEST_ENQUEUEDrequest_id, url, method, surface_id, priority
REQUEST_SKIPPED_DUPLICATEurl, normalized_url, existing_request_id
REQUEST_SKIPPED_SCOPEurl, reason
FETCH_STARTrequest_id, url, attempt
FETCH_OKrequest_id, status, final_url, bytes, duration_ms
FETCH_RETRYrequest_id, reason, retry_count, next_delay
FETCH_FAILEDrequest_id, error_code, error_detail
BROWSER_FALLBACKrequest_id, trigger_reason
LINKS_EXTRACTEDrequest_id, discovered, accepted, skipped
CANDIDATE_EMITTEDrequest_id, candidate_id, final_url
CHECKPOINT_SAVEDstate_version, pending, fetched, failed, candidates
SOURCE_EXHAUSTEDreason, totals
CRAWL_STOPPEDstatus, reason

09 / Termination conditions

IDTriggerMeaning
T-01All approved seed/surface queues emptyNormal exhaustion.
T-02No new unique in-scope URLs after bounded traversalNormal exhaustion.
T-03Pagination repeat/loop signature reachedNormal branch termination.
T-04Owner/process cancellationStop safely after checkpoint.
T-05Critical plan contradictionPause/FAILED; do not silently widen scope.
T-06Protection/login/CAPTCHA blocks essential corpusPARTIAL/BLOCKED; no bypass.
T-07Fatal persistence failureFAILED; preserve last known safe state.
T-08Safety/SSRF violation attemptBLOCK request, log, continue or fail according to severity.

10 / Resume and checkpoint contract

RequirementContract
Persistent queuePending/fetched/skipped state survives worker/process restart.
Idempotent enqueueSame normalized request in same job does not create duplicate work.
Atomic checkpointQueue + counters + cursor/surface state must not diverge.
Fetch in-flightAfter crash, in-flight request may safely be retried.
Candidate emissionCandidate store must have idempotency key so crash does not duplicate downstream candidate.
Plan immutabilityActive run uses one plan snapshot/version; plan change creates controlled resume/migration or new run.
State versionEvery checkpoint increments or records a monotonic state version.
No log dependencyResume depends on state store, not reconstructing progress from console logs.
Console log is not state.

После перезапуска система не должна читать старые лог-строки и угадывать прогресс. Очередь, request statuses, surface cursors и counters должны жить в устойчивом state store.

11 / Failure modes

IDFailureRequired behavior
F-05-01DNS failureBound retries; mark request failed; if source root unavailable, job may fail early.
F-05-02TimeoutRetry bounded times, then fail request.
F-05-03429/rate limitHonor Retry-After/backoff and reduce crawl pace.
F-05-04403/challengeDo not rotate stealth identity automatically; mark blocked and evaluate source coverage.
F-05-05Redirect loopStop after bounded redirects; error event.
F-05-06Malformed HTML/XMLStore fetch success but parse failure; continue other URLs.
F-05-07Huge sitemapStream/process incrementally; do not load unbounded XML into memory.
F-05-08Huge page bodyAbort/skip after configured safe size.
F-05-09Queue storage unavailableStop safely; do not run stateless and lose resume guarantees.
F-05-10Browser crashRetry only browser-required request within bounded policy; do not switch whole crawl to browser.
F-05-11Unexpected new hostSkip and log; do not auto-expand source scope.
F-05-12Crawler discovers millions of URLsTrip configurable safety ceiling and require review before continuing.

12 / Definition of Done

IDCriterion
A-05-01Crawler refuses to run without an approved crawl_plan snapshot.
A-05-02Every fetched URL is attributable to an approved surface/discovery method.
A-05-03Same request URL is not fetched repeatedly due to duplicate discovery paths.
A-05-04External/disallowed/private-network URLs are never fetched as normal corpus requests.
A-05-05HTTP path is the default; browser path is measurable and exceptional.
A-05-06429/5xx/timeout retry behavior is bounded and visible in logs.
A-05-07Crash/restart resumes without rebuilding the whole queue from scratch.
A-05-08Candidate emission is idempotent across restart.
A-05-09Crawler can terminate normally without guessing that more pages 'might' exist.
A-05-10Crawler never invents pages to reach 30 records.
A-05-11Crawler events provide enough context for operator/AI diagnosis.
A-05-12A forced-stop integration test proves resume behavior.
A-05-13A loop-trap fixture proves pagination/sitemap loops terminate.
A-05-14A cross-domain redirect fixture proves out-of-scope destinations are blocked.
A-05-15Large sitemap/page fixtures do not require unbounded memory.

13 / Luna Medium implementation blocks

BlockScopeExpected outcome
LUNA-05-ARequest model + normalizationDefine request schema, normalization unit tests, no network.
LUNA-05-BScope guardAllowed hosts/paths/schemes/file types + redirect scope tests.
LUNA-05-CPersistent queue adapterEnqueue/dedupe/status transitions/checkpoint storage.
LUNA-05-DHTTP fetch workerTimeout/retry/status/content-type/body-size handling.
LUNA-05-ELink extraction + traversal authorizationOnly crawl_plan-authorized surfaces/links.
LUNA-05-FCandidate emitterIdempotent downstream candidate handoff.
LUNA-05-GBrowser fallback adapterOnly after HTTP-only path works and benchmark requires it.
LUNA-05-HResume/failure integration suiteForced kill, restart, duplicate prevention, loop traps.
Не объединять всё в один coding prompt.

Каждый bounded block имеет свои unit/integration tests и evidence. Browser fallback добавляется только после работающего HTTP crawler и только если benchmark показывает реальную необходимость.

14 / Handoff

NEXT PLANNING ARTIFACT Statiya_poluchatel_1_06_ARTICLE_DETECTION_FILTERING.html SP-06 receives: - fetched candidate URL - final_url - title/meta/DOM snapshot or parsed signals - discovery_method - surface_id - content_type - canonical/redirect evidence - fetch status - source/job identity SP-06 returns: INCLUDE / EXCLUDE + reason + evidence + extracted visible title/canonical URL candidate