跳到正文
DEV Community· MortimerNilsson7694·· 3 小時前AI 評分54

新聞監測檢索架構如何設定抓取邊界與引用溯源

Grounded News Monitoring Retrieval Architecture — Crawl Boundaries That Hold

AI 導讀

新聞監測檢索架構應先明確限定可抓取的主機與路徑、新鮮度窗口和文件大小上限,並讓引用記錄貫穿資料轉換流程。文章建議以詞彙搜尋和 metadata 篩選起步,只有在標註資料顯示同義詞造成漏檢時才加入向量重排;每個文本區塊需保留來源資料及原文偏移位置,生成的聲明則須帶有有效引用 ID。

正文

Short answer: for a news monitoring service, keep crawl boundaries explicit before retrieval: allowlisted hosts, a freshness window, a document-size cap, and a citation record that survives every transformation. Start with a small lexical index plus metadata filters; add vector reranking only after the grounded answer passes citation tests.

News monitoring is a retrieval problem before it is a generation problem. The service has to decide what it is allowed to fetch, what counts as the same story, and which text can support a sentence in the final alert. A clever prompt cannot repair a crawler that quietly crossed a tenant boundary.

I build developer tools, so my first metric is time-to-first-call. My second is how much configuration a new contributor must understand. A boundary that lives in one typed function is easier to review than a dozen environment flags scattered through workers. Fast is useful. Predictable is better.

A decision matrix for grounded monitoring

Design choice Default for a small service Change it when
Crawl scope Explicit host and path allowlist Legal or editorial policy grants a wider feed
Freshness Store fetch time and enforce a query window Users need historical investigations
Chunking Paragraph-aware chunks with source offsets Documents are mostly tables or transcripts
Retrieval Lexical search, then optional vector rerank Synonyms routinely hide relevant wording
Citation URL, title, published time, and character offsets A source cannot provide stable offsets
Re-crawl Conditional requests and a bounded queue A publisher requires a scheduled feed

The recommendation is intentionally boring: make the crawl contract executable, keep raw documents immutable, and attach provenance to every chunk. It gives an editor a way to reject an unsupported alert instead of arguing with a model's confidence score.

Boundaries are boring. That is why they work.

The original retrieval-augmented generation paper describes a generator conditioned on retrieved passages rather than on model memory alone. That distinction matters here. Retrieval can improve grounding, but only if the passages came from an approved corpus and the answer can point back to them.

How should a retrieval architecture handle news monitoring service crawl boundaries?

Treat the boundary as a policy object, not a comment in a crawler. A policy should answer four questions for each request: which host and path are allowed, which robots or rate limits apply, how old a document may be, and how large a response may become. The fetcher returns a typed rejection when a check fails. No downstream stage receives a half-approved document.

Here is the smallest shape I use in TypeScript. It is a pure decision function, so tests can cover it without a network call.

type CrawlPolicy = {
  hosts: Set<string>;
  pathPrefixes: string[];
  maxBytes: number;
  maxAgeHours: number;
};

type CrawlDecision =
  | { allowed: true; url: URL }
  | { allowed: false; reason: string };

export function checkCrawl(urlText: string, now: Date, policy: CrawlPolicy): CrawlDecision {
  let url: URL;
  try {
    url = new URL(urlText);
  } catch {
    return { allowed: false, reason: "invalid URL" };
  }

  if (url.protocol !== "https:") {
    return { allowed: false, reason: "HTTPS is required" };
  }
  if (!policy.hosts.has(url.hostname)) {
    return { allowed: false, reason: "host is outside the allowlist" };
  }
  if (!policy.pathPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {
    return { allowed: false, reason: "path is outside the allowlist" };
  }
  if (policy.maxBytes <= 0 || policy.maxAgeHours <= 0) {
    return { allowed: false, reason: "policy limits must be positive" };
  }

  return { allowed: true, url };
}

The byte cap belongs at the streaming HTTP layer as well; checking it after buffering defeats the point. Record the response status, content type, final URL, and fetch timestamp beside the raw body. A redirect should be evaluated again, because an allowed host can redirect to an unapproved host. Keep that rule visible in the worker code.

I also separate discovery from fetching. RSS or sitemap entries are candidates, not permission. The same policy function runs after discovery and before the request. This catches a common failure mode: a broad feed imports a press-release domain that the account never intended to monitor. In practice, the queue carries the discovered URL, the tenant's policy version, and the reason the URL was discovered. A worker loads the current policy, compares the version, checks the hostname and path, and only then opens a connection. If the publisher redirects from /story/42 to a different host, the worker evaluates the final URL with the same checks; it does not inherit approval from the first hop. I log the rejection with a stable reason code and retain the candidate for inspection, because deleting it makes editorial debugging impossible. This extra bookkeeping is less code than explaining to a customer why an alert cited a page they never allowed.

What makes a news document citable after retrieval?

A citation is data, not formatting added at the end. Store a source record with a canonical URL, publisher label, title, published timestamp, fetched timestamp, and a content hash. Each chunk carries the source record plus start and end offsets into the normalized text. When a parser changes whitespace, keep the raw body and normalization version so an editor can reproduce the quoted span.

Deduplication needs the same discipline. Two URLs can describe one wire story; one URL can change underneath you. Hash the normalized article for a first pass, then use a similarity check for near-duplicates. Do not merge records until their publisher, publication time, and canonical link agree with your policy. Otherwise a later rewrite can inherit an earlier citation by accident.

The alert pipeline should fail closed. If retrieval returns a chunk without offsets or a source outside the policy, mark it ineligible for generation and expose the reason in telemetry. A model may still summarize eligible passages. It must not fill the gap with an uncited guess.

Short checks catch expensive mistakes. I keep fixtures for an off-allowlist redirect, an article older than the requested window, a response that crosses the byte cap, and two pages with identical content under different URLs. The fixture names are plain English; the assertion output includes the policy reason. That makes a failing build actionable at 2 a.m.

A retrieval loop that preserves provenance

The query path can stay small. Parse the user's topic and time window, apply metadata filters, run lexical retrieval, optionally rerank the top candidates, and pass only chunks that still carry source offsets to the generator. The generator's output schema should require citation IDs for each claim. A post-check rejects a claim whose ID is missing from the retrieved set.

type Chunk = {
  id: string;
  text: string;
  sourceId: string;
  start: number;
  end: number;
  publishedAt: string;
};

type Claim = { text: string; citationIds: string[] };

export function eligible(chunks: Chunk[], cutoff: Date): Chunk[] {
  return chunks.filter((chunk) => {
    const published = Date.parse(chunk.publishedAt);
    return Number.isFinite(published)
      && published >= cutoff.getTime()
      && chunk.start >= 0
      && chunk.end > chunk.start
      && chunk.text.length > 0;
  });
}

export function claimsAreGrounded(claims: Claim[], chunks: Chunk[]): boolean {
  const ids = new Set(chunks.map((chunk) => chunk.id));
  return claims.every((claim) =>
    claim.citationIds.length > 0
      && claim.citationIds.every((id) => ids.has(id)),
  );
}

The code does not rank anything. That is deliberate. Ranking quality is workload-specific, while provenance invariants are not. Benchmark both: retrieval recall on a labeled set, and citation validity on generated alerts. A high recall score with broken citations is a failed monitoring service.

When are wider boundaries or a different design justified?

The catch is editorial scope. An allowlist is unsuitable for open-web discovery, where the business explicitly wants unknown publishers. In that case, put discovery in a quarantine corpus, attach a review state, and keep it out of customer alerts until a person or policy promotes the source. Do not silently widen the production index.

A tight freshness window is also wrong for investigations that ask what was reported months ago. Keep historical storage, but make the query window explicit and visible in the result. A vector index may be unnecessary when headlines use stable terms; lexical search is easier to inspect and cheaper to operate. Add embeddings when labeled misses show a synonym problem, then compare the reranker against the lexical baseline.

Your mileage may vary. I am not sure a single chunk size works across local news, wire copy, and long interviews. Measure citation span accuracy on each source class, and let the data choose the split points.

The practical decision rule is simple: choose the least complex retrieval stack that meets a measured recall target while keeping every generated claim traceable. Expand crawl scope, ranking machinery, or retention only when a test demonstrates the need. That keeps the service useful to editors and understandable to the next engineer who has to change it.

References

Further reading

來源:DEV Community · dev.to