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

金融研究儀錶板檢索架構:四項關鍵查詢限制

Financial Research Dashboard Retrieval Architecture — 4 Query Limits That Matter

AI 導讀

這篇架構決策紀錄建議金融研究儀錶板採用兩階段檢索,並為候選頁面、每頁區塊、證據總量及證據時效設定明確上限。系統先選取頁面版本,再於所選版本內檢索,並為每個區塊保留內容雜湊、來源網址、版本識別碼、觀測時間和字元偏移,以建立可追溯的稽核鏈。若索引版本落後最新已接受的觀測版本,服務不能聲稱資料為最新;新鮮證據不足時,答案應標示為不完整。

正文

Use a two-stage retrieval path with explicit budgets for candidate documents, chunks, freshness, and model context; for a financial research dashboard that watches gaming-company web pages and alerts on diffs, this keeps a changed disclosure searchable without letting one broad query consume the entire retrieval budget.

The deciding constraint is not raw index size. It is whether every answer can be traced to the exact page version that was current when retrieval ran. A dashboard that summarizes an old investor-relations page accurately is still wrong. The architecture must therefore treat freshness as an invariant, not as a background indexing preference, and it must reject or qualify an answer when that invariant cannot be established.

Freshness is correctness.

This is an architecture decision record, not a ranking of search engines. The recommendation assumes that the dashboard needs attributable research rather than open-ended web discovery. It also assumes that page monitoring produces immutable versions and a structured diff before the retrieval layer sees the content.

Decision record: bound retrieval at four explicit points

The four limits are candidate pages, chunks per page, total evidence chunks, and maximum evidence age. They belong in one request policy because changing any one of them changes the meaning of the others. Raising the candidate-page limit while leaving the total chunk limit fixed, for example, gives each page less opportunity to contribute evidence; raising chunks per page can let a long annual report crowd out a short, recent correction.

The selected design separates document selection from passage selection. Stage one ranks page versions using the research query, issuer identity, document class, publication time, and observed time. Stage two searches only within the selected immutable versions, then applies per-page and global caps before assembling model context. Each returned chunk carries a content hash, source URL, page-version identifier, observation timestamp, and character offsets. Those fields form the audit trail from a sentence in the dashboard back to frozen evidence.

Four invariants govern the path:

  1. A retrieval result refers to one immutable page version; chunks from different versions of the same page cannot be silently combined.
  2. The newest eligible version wins unless the query explicitly asks for historical state.
  3. No page may consume the whole evidence budget.
  4. An answer without sufficient fresh evidence is labeled incomplete rather than padded with weak matches.

That last rule is easy to soften under deadline pressure. Don't. An exactly-once mindset is useful here even though web crawling itself cannot promise exactly-once delivery: deduplicate observations by content hash, make indexing idempotent, and record every transition. Duplicate fetches then become harmless repeated inputs instead of duplicate evidence.

The failure boundary is sharp. Fetching and diffing may continue while indexing is delayed, but the query service must compare its indexed version with the latest accepted observation before claiming freshness. If those identifiers differ, it can still return the last verified version with an explicit stale status; it cannot present that result as current.

How should a financial research dashboard enforce retrieval query limits?

Enforce them in the retrieval service, before context reaches the language model, and log both the configured limits and the actual counts for every request. A prompt instruction such as "use only eight passages" is not a control boundary because the expensive and potentially noisy search has already happened. The service owns admission, ranking, truncation, and provenance; the model receives a bounded evidence envelope.

The exact numbers are workload decisions, not universal facts. A reasonable review process starts with named policy values, runs a labeled query set, and changes one value at a time. I'm not sure that any fixed chunk count survives contact with every filing style; the evidence needed to settle it is a recall audit across the dashboard's actual issuer pages, including long reports, short corrections, tables, and navigation-heavy updates.

Limit Protects against Failure signal Tuning question
Candidate pages Broad queries scanning unrelated versions Relevant issuer or document class disappears before passage ranking Does metadata filtering remove known relevant pages?
Chunks per page One long document monopolizing context Other independently relevant pages never appear Can a second source contribute evidence?
Total evidence chunks Unbounded latency and diluted context Low-ranked passages enter the evidence envelope Does each admitted chunk support a claim?
Maximum evidence age Fluent answers grounded in superseded pages Indexed version trails the latest accepted observation Should the request wait, return stale, or abstain?

Chunking is where these limits become real. Split on document structure first: headings, paragraphs, list items, table rows, and disclosure sections convey boundaries that a blind character window ignores. Then apply a size ceiling with modest overlap only where a sentence or table crosses a boundary. Store the parent section and page version on every chunk. This makes the unit of retrieval small enough for focused matching while preserving enough hierarchy to reconstruct meaning, and it prevents a tiny navigation edit from forcing the system to treat an entire page as newly relevant. A web diff should not be embedded as a loose bag of added and removed lines. Persist the old and new page versions, compute the diff between their normalized representations, and attach changed-region identifiers to chunks in the new version. Retrieval can boost those regions for a question about recent changes without deleting unchanged context that explains them. For a gaming-company research dashboard, a changed revenue sentence may require the unchanged section heading, period label, and footnote to be interpretable; the diff is a routing signal, not sufficient evidence by itself. Freshness also has two clocks. Publication time is what the page or document declares, while observation time is when the monitor captured it. Keep both. A corrected page may retain its original publication date, and relying on that date alone can make the correction look old even though its content hash and observation time are new. This is precisely the sort of detail that matters in reconciliation: source state, observed state, and indexed state must be distinct records.

No silent mixing.

The critical path in Go

The following code sketches the policy boundary. The values are illustrative configuration for a test deployment, not claimed optimums. More important than the values is that one policy object controls admission and that the response exposes what happened.

package retrieval

import (
    "context"
    "errors"
    "sort"
    "time"
)

type Policy struct {
    MaxCandidatePages int
    MaxChunksPerPage  int
    MaxEvidenceChunks int
    MaxEvidenceAge    time.Duration
}

type Query struct {
    Text       string
    IssuerID   string
    AsOf       time.Time
    Historical bool
}

type Chunk struct {
    PageVersionID string
    SourceURL     string
    ContentHash   string
    ObservedAt    time.Time
    StartOffset   int
    EndOffset     int
    Score         float64
}

type Result struct {
    Chunks       []Chunk
    CandidateCnt int
    Fresh        bool
    Policy       Policy
}

type Index interface {
    CandidateVersions(context.Context, Query, int) ([]string, error)
    Chunks(context.Context, Query, []string) ([]Chunk, error)
    LatestObservedVersion(context.Context, string) (string, error)
}

func Retrieve(ctx context.Context, idx Index, q Query, p Policy) (Result, error) {
    if p.MaxCandidatePages < 1 || p.MaxChunksPerPage < 1 ||
        p.MaxEvidenceChunks < 1 || p.MaxEvidenceAge <= 0 {
        return Result{}, errors.New("invalid retrieval policy")
    }

    versions, err := idx.CandidateVersions(ctx, q, p.MaxCandidatePages)
    if err != nil {
        return Result{}, err
    }
    chunks, err := idx.Chunks(ctx, q, versions)
    if err != nil {
        return Result{}, err
    }

    sort.SliceStable(chunks, func(i, j int) bool {
        return chunks[i].Score > chunks[j].Score
    })

    perPage := make(map[string]int)
    selected := make([]Chunk, 0, p.MaxEvidenceChunks)
    fresh := true
    for _, chunk := range chunks {
        if perPage[chunk.PageVersionID] >= p.MaxChunksPerPage {
            continue
        }
        if !q.Historical && q.AsOf.Sub(chunk.ObservedAt) > p.MaxEvidenceAge {
            fresh = false
            continue
        }
        latest, err := idx.LatestObservedVersion(ctx, chunk.SourceURL)
        if err != nil {
            return Result{}, err
        }
        if !q.Historical && latest != chunk.PageVersionID {
            fresh = false
            continue
        }

        selected = append(selected, chunk)
        perPage[chunk.PageVersionID]++
        if len(selected) == p.MaxEvidenceChunks {
            break
        }
    }

    return Result{
        Chunks:       selected,
        CandidateCnt: len(versions),
        Fresh:        fresh,
        Policy:       p,
    }, nil
}

Production code should fetch latest-version metadata in one batch rather than once per chunk, but the example leaves that optimization visible as an interface concern. More importantly, the request time AsOf is passed in rather than read repeatedly from the system clock. Tests can now reproduce the same age decision, and an audit record can explain why a chunk was admitted at that instant.

The audit event should include a query identifier, a hash of the normalized query, policy version, candidate version IDs, admitted chunk hashes, exclusion reasons, index snapshot identifier, and final freshness state. Avoid logging raw confidential research queries unless the retention and access policy permits it. Financial research workflows can contain material assumptions or client-specific interests; observability does not override data minimization, retention schedules, or access controls.

Failure boundaries, tests, and operations

Test the architecture as a state machine. Begin with version A indexed and current, retrieve it, then accept version B from the page monitor without indexing it. The next current-state query must not claim that A is fresh. After B is indexed, repeated delivery of the same content hash must leave one logical page version and the same searchable chunks. Finally, issue a historical query whose AsOf selects A and verify that the freshness rule does not incorrectly force B into the result.

One focused test is worth pages of policy prose: create a long page with many high-scoring chunks and a short page containing one decisive changed sentence. The per-page cap should preserve room for the short page, while the total evidence cap remains fixed. Then remove the short page from the candidate set. The resulting recall failure belongs to stage one, which tells the team to inspect metadata filters and candidate limits rather than retuning chunk size at random.

Watch distributions, not a single latency average. Useful operational measures include candidate count, chunks considered, chunks admitted, age of the newest indexed observation, fraction of requests marked stale, abstention count, and exclusion reason. Break them down by document class and issuer because an aggregate can hide a crawler or parser problem isolated to one page template. Keep the policy version beside those measures so a change in results can be reconciled with a deliberate configuration change.

Deployment should be reversible. Build the new chunker beside the old one, write to a versioned index, and replay the same labeled queries against both snapshots. The acceptance question is not "does the new score look higher?" It is whether known evidence remains retrievable, stale versions are excluded correctly, citations resolve to exact content hashes, and the bounded request stays within the operational envelope chosen by the team.

Compliance limits deserve their own review. Immutable evidence improves auditability, but indefinite retention may conflict with contractual or regulatory deletion duties. The architecture therefore needs a retention decision above the index: deleting a source version must also delete or tombstone its derived chunks and prevent cached answers from citing it. The correct retention period cannot be inferred from retrieval quality; counsel, data classification, jurisdiction, and the source license resolve it.

Rejected option and where it still fits

The rejected option is a single-stage global chunk search with a top-k limit and no page-version gate. It is attractive because the request path is short, and it can be suitable for a small, static, internally curated corpus where documents are replaced only through a controlled release and historical state is irrelevant. Stick with that simpler design when the corpus owner can prove those conditions and the cost of a stale result is low.

The catch is that a monitored public web page violates those assumptions. Old and new chunks can coexist, a long document can dominate the ranking, and a top-k value says nothing about source diversity or freshness. Adding a larger context window does not repair the evidence selection error; it merely gives the model more potentially conflicting text.

The two-stage design is also not suitable when the product is general web search, where candidate discovery across an open corpus is the central job rather than a bounded issuer-and-document lookup. In that case, broader discovery and independent freshness estimation are required. For the financial research dashboard described here, however, explicit source scope is an advantage: it permits deterministic version checks, finite query budgets, and an audit trail that can be reconciled after an alert fires.

The decision rule is concise. Choose bounded two-stage retrieval when current source state and attributable diffs matter more than maximum exploratory recall; choose the simpler global search only when the corpus is controlled, static, and low consequence. Query limits are then part of correctness, not merely performance tuning.

References

來源:DEV Community · dev.to