Read immutable crawl_plan snapshot for this run.
01 / Граница ответственности
SP-05 отвечает за discovery/fetch/queue/resume. Он не решает окончательно, что является статьёй. Он передаёт кандидатов в SP-06 вместе с evidence о том, откуда URL был найден и как был получен.
Если crawler видит новый домен, новую ветку URL или неожиданную структуру, которая не описана crawl_plan, он логирует это и пропускает/ставит review condition. Он не начинает исследовать новый интернет сам.
02 / Канонический pipeline
Create initial request set from approved sitemap/feed/archive/listing nodes.
Canonicalize request URL for request-level dedup only.
Reject external/private/disallowed hosts or paths.
Persist request with source, parent, depth, discovery method and priority.
HTTP-first fetch with timeout/retry/rate policy.
Extract only links relevant to approved traversal nodes/patterns.
Pass likely content pages to candidate store/classifier input.
Persist queue/visited/counters so restart is safe.
Stop when approved traversal graph is exhausted or explicit blocker fires.
03 / Request record
| Field | Meaning |
|---|---|
| request_id | Stable crawl-request identity for this run. |
| job_id | Owning job. |
| source_id | Owning source/dataset. |
| url_original | URL as discovered. |
| url_normalized | Request-dedup normalized URL. |
| parent_request_id | Discovery parent, if any. |
| discovery_method | sitemap / feed / archive / category / pagination / page-link / browser. |
| surface_id | crawl_plan node that authorized this request. |
| depth | Traversal depth relative to source seed. |
| priority | Deterministic queue priority. |
| status | PENDING / FETCHING / FETCHED / SKIPPED / FAILED / BLOCKED. |
| http_status | Final HTTP status if fetched. |
| content_type | Response content type. |
| redirect_chain[] | Observed redirects. |
| final_url | Final fetched URL after redirects. |
| fetched_at | Timestamp. |
| retry_count | Retries already used. |
| error_code | Normalized failure code. |
| error_detail | Short diagnostic text, safe for logs. |
| candidate_emitted | Whether sent to article candidate layer. |
| checkpoint_version | Job state version that includes this request. |
04 / URL normalization
| ID | Rule | Contract |
|---|---|---|
| N-01 | Scheme/host casing | Lowercase scheme and hostname. |
| N-02 | Fragments | Drop URL fragment for request identity. |
| N-03 | Default ports | Normalize :80/:443 where equivalent. |
| N-04 | Dot segments | Resolve path dot-segments safely. |
| N-05 | Trailing slash | Do not globally collapse slash/non-slash unless source-specific redirect/canonical evidence proves equivalence. |
| N-06 | Query params | Do not strip all query parameters. Remove only source-proven tracking/session params; preserve pagination/content parameters. |
| N-07 | Percent encoding | Normalize only safe equivalent forms; avoid changing path semantics. |
| N-08 | Canonical tag | Do not use canonical tag as request identity before fetch; store it later for logical-article dedup. |
| N-09 | Redirects | Final redirected URL may become preferred request target for future duplicates, but historical request evidence remains. |
| N-10 | Titles | Never dedupe URLs by page title. |
SP-05 предотвращает повторную загрузку одного и того же request URL. Решение, что два разных URL ведут на один логический материал, относится к SP-07 и использует canonical/redirect evidence.
05 / Scope guard
| ID | Rule | Required behavior |
|---|---|---|
| S-01 | Allowed hosts | Only hosts explicitly approved by crawl_plan may be fetched. |
| S-02 | Subdomains | Not automatically included. Must be approved or verified canonical variant. |
| S-03 | External links | Ignore by default; they are not source corpus. |
| S-04 | Private/local targets | Reject via SSRF/private network checks; detailed implementation belongs to SP-13. |
| S-05 | Schemes | Allow http/https only for crawler requests. |
| S-06 | File types | Skip obvious non-HTML corpus assets: images, video, archives, binaries, fonts, stylesheets. |
| S-07 | Utility endpoints | Skip logout/login/cart/account/search unless explicitly part of source traversal plan. |
| S-08 | Calendar traps | Bound date/archive traversal to discovered evidence; do not generate infinite dates. |
| S-09 | Pagination loops | Visited normalized listing URLs + repeated-content/page signature stop conditions. |
| S-10 | Generated URLs | Crawler may follow discovered URLs, not invent combinatorial parameter spaces. |
06 / Fetch policy
| Area | Policy |
|---|---|
| HTTP first | Use normal HTTP client/crawler path for all pages by default. |
| Browser fallback | Allowed only for surface/page class proven to require JS rendering. |
| Timeout | Bound connect/read/overall timeout; no request can block worker indefinitely. |
| Retries | Small bounded retries only for transient network/5xx/429 classes. |
| 4xx | Most 4xx are terminal except source-specific retryable cases. |
| 429 | Respect Retry-After where present; reduce rate rather than hammering. |
| 5xx | Retry with bounded exponential backoff, then mark FAILED. |
| Redirects | Bound redirect count; reject redirect to disallowed host. |
| Content type | Parse HTML/XML/feed only as appropriate; do not feed binaries to parser. |
| Body size | Set safe max response size; very large responses need explicit handling. |
| TLS | Verify TLS normally; do not disable certificate verification to make crawl 'work'. |
| Compression | Allow standard gzip/br but count decompressed size for limits. |
Каждый переход в Playwright/browser path должен иметь trigger reason и отдельный log event. Доля browser requests должна быть видна в run summary.
07 / Queue priority and traversal
| Priority | Class | Why |
|---|---|---|
| P0 | robots/sitemap topology | Needed to understand and enumerate source structure. |
| P1 | approved archive/category/listing pages | Primary traversal surfaces. |
| P2 | candidate article pages | Content candidates discovered from authoritative surfaces. |
| P3 | secondary pagination/listing expansions | Continue known traversal. |
| P4 | fallback page-link discovery | Only if crawl_plan allows it. |
08 / Structured crawler events
| Event | Minimum payload |
|---|---|
| CRAWL_START | job_id, plan_id, source_id, seed_count |
| REQUEST_ENQUEUED | request_id, url, method, surface_id, priority |
| REQUEST_SKIPPED_DUPLICATE | url, normalized_url, existing_request_id |
| REQUEST_SKIPPED_SCOPE | url, reason |
| FETCH_START | request_id, url, attempt |
| FETCH_OK | request_id, status, final_url, bytes, duration_ms |
| FETCH_RETRY | request_id, reason, retry_count, next_delay |
| FETCH_FAILED | request_id, error_code, error_detail |
| BROWSER_FALLBACK | request_id, trigger_reason |
| LINKS_EXTRACTED | request_id, discovered, accepted, skipped |
| CANDIDATE_EMITTED | request_id, candidate_id, final_url |
| CHECKPOINT_SAVED | state_version, pending, fetched, failed, candidates |
| SOURCE_EXHAUSTED | reason, totals |
| CRAWL_STOPPED | status, reason |
09 / Termination conditions
| ID | Trigger | Meaning |
|---|---|---|
| T-01 | All approved seed/surface queues empty | Normal exhaustion. |
| T-02 | No new unique in-scope URLs after bounded traversal | Normal exhaustion. |
| T-03 | Pagination repeat/loop signature reached | Normal branch termination. |
| T-04 | Owner/process cancellation | Stop safely after checkpoint. |
| T-05 | Critical plan contradiction | Pause/FAILED; do not silently widen scope. |
| T-06 | Protection/login/CAPTCHA blocks essential corpus | PARTIAL/BLOCKED; no bypass. |
| T-07 | Fatal persistence failure | FAILED; preserve last known safe state. |
| T-08 | Safety/SSRF violation attempt | BLOCK request, log, continue or fail according to severity. |
10 / Resume and checkpoint contract
| Requirement | Contract |
|---|---|
| Persistent queue | Pending/fetched/skipped state survives worker/process restart. |
| Idempotent enqueue | Same normalized request in same job does not create duplicate work. |
| Atomic checkpoint | Queue + counters + cursor/surface state must not diverge. |
| Fetch in-flight | After crash, in-flight request may safely be retried. |
| Candidate emission | Candidate store must have idempotency key so crash does not duplicate downstream candidate. |
| Plan immutability | Active run uses one plan snapshot/version; plan change creates controlled resume/migration or new run. |
| State version | Every checkpoint increments or records a monotonic state version. |
| No log dependency | Resume depends on state store, not reconstructing progress from console logs. |
После перезапуска система не должна читать старые лог-строки и угадывать прогресс. Очередь, request statuses, surface cursors и counters должны жить в устойчивом state store.
11 / Failure modes
| ID | Failure | Required behavior |
|---|---|---|
| F-05-01 | DNS failure | Bound retries; mark request failed; if source root unavailable, job may fail early. |
| F-05-02 | Timeout | Retry bounded times, then fail request. |
| F-05-03 | 429/rate limit | Honor Retry-After/backoff and reduce crawl pace. |
| F-05-04 | 403/challenge | Do not rotate stealth identity automatically; mark blocked and evaluate source coverage. |
| F-05-05 | Redirect loop | Stop after bounded redirects; error event. |
| F-05-06 | Malformed HTML/XML | Store fetch success but parse failure; continue other URLs. |
| F-05-07 | Huge sitemap | Stream/process incrementally; do not load unbounded XML into memory. |
| F-05-08 | Huge page body | Abort/skip after configured safe size. |
| F-05-09 | Queue storage unavailable | Stop safely; do not run stateless and lose resume guarantees. |
| F-05-10 | Browser crash | Retry only browser-required request within bounded policy; do not switch whole crawl to browser. |
| F-05-11 | Unexpected new host | Skip and log; do not auto-expand source scope. |
| F-05-12 | Crawler discovers millions of URLs | Trip configurable safety ceiling and require review before continuing. |
12 / Definition of Done
| ID | Criterion |
|---|---|
| A-05-01 | Crawler refuses to run without an approved crawl_plan snapshot. |
| A-05-02 | Every fetched URL is attributable to an approved surface/discovery method. |
| A-05-03 | Same request URL is not fetched repeatedly due to duplicate discovery paths. |
| A-05-04 | External/disallowed/private-network URLs are never fetched as normal corpus requests. |
| A-05-05 | HTTP path is the default; browser path is measurable and exceptional. |
| A-05-06 | 429/5xx/timeout retry behavior is bounded and visible in logs. |
| A-05-07 | Crash/restart resumes without rebuilding the whole queue from scratch. |
| A-05-08 | Candidate emission is idempotent across restart. |
| A-05-09 | Crawler can terminate normally without guessing that more pages 'might' exist. |
| A-05-10 | Crawler never invents pages to reach 30 records. |
| A-05-11 | Crawler events provide enough context for operator/AI diagnosis. |
| A-05-12 | A forced-stop integration test proves resume behavior. |
| A-05-13 | A loop-trap fixture proves pagination/sitemap loops terminate. |
| A-05-14 | A cross-domain redirect fixture proves out-of-scope destinations are blocked. |
| A-05-15 | Large sitemap/page fixtures do not require unbounded memory. |
13 / Luna Medium implementation blocks
| Block | Scope | Expected outcome |
|---|---|---|
| LUNA-05-A | Request model + normalization | Define request schema, normalization unit tests, no network. |
| LUNA-05-B | Scope guard | Allowed hosts/paths/schemes/file types + redirect scope tests. |
| LUNA-05-C | Persistent queue adapter | Enqueue/dedupe/status transitions/checkpoint storage. |
| LUNA-05-D | HTTP fetch worker | Timeout/retry/status/content-type/body-size handling. |
| LUNA-05-E | Link extraction + traversal authorization | Only crawl_plan-authorized surfaces/links. |
| LUNA-05-F | Candidate emitter | Idempotent downstream candidate handoff. |
| LUNA-05-G | Browser fallback adapter | Only after HTTP-only path works and benchmark requires it. |
| LUNA-05-H | Resume/failure integration suite | Forced kill, restart, duplicate prevention, loop traps. |
Каждый bounded block имеет свои unit/integration tests и evidence. Browser fallback добавляется только после работающего HTTP crawler и только если benchmark показывает реальную необходимость.