Forward Deployed EngineeringAI EngineeringDocument Processing and RAG
How would you chunk contracts, Slack threads, and PDFs full of tables: same pipeline or different?
Question 24 of 73 · Updated
On this page
- Interview-ready answer
- 1. Shared pipeline, different document semantics
- 2. End-to-end ingestion architecture
- 3. Contracts: preserve legal structure and dependencies
- Parsing
- Chunking
- Metadata and retrieval
- 4. Slack: preserve conversational context, not just messages
- Parsing
- Chunking
- Metadata and lifecycle
- 5. PDFs full of tables: preserve layout and cell semantics
- Parse before chunking
- Table-aware representations
- Exact numeric questions
- 6. Parent-child retrieval and evidence assembly
- 7. A common chunk contract
- 8. Tested Python example: pack structured units without losing context
- 9. Evaluate chunking against the actual customer tasks
- 10. Production trade-offs
- Likely interviewer follow-ups
Interview-ready answer#
I would use the same overall ingestion and retrieval architecture, but different parsing and chunking strategies for each document type. A chunk should be a meaningful, retrievable evidence unit, not simply the next 500 tokens.
For contracts, I would preserve the hierarchy of articles, sections, clauses, definitions, exceptions and cross-references. For Slack, I would use conversation-aware chunks that preserve the thread root, relevant replies, chronology and decision context. For table-heavy PDFs, I would extract layout and table structure first, then group rows while repeating the applicable headers, units and captions. Flattening a table into arbitrary text windows can destroy the relationship between a value and its row or column.
All three would share a versioned chunk schema, source provenance, permission enforcement, embedding and lexical indexing, evaluation and lifecycle management. I would use smaller retrieval units linked to larger authorized context when necessary, enforce the actual embedding model's input limits, and measure evidence recall, citation correctness, answer quality, latency and cost against a representative customer dataset. The objective is to retrieve sufficient correct evidence, not to make all chunks the same size.
1. Shared pipeline, different document semantics#
Chunking transforms a parsed source into units that can be indexed and retrieved. The appropriate unit depends on how the source conveys meaning.
| Source | Natural evidence unit | Context that must be preserved | Typical failure with fixed windows |
|---|---|---|---|
| Contract | Clause or coherent subclause | Section hierarchy, defined terms, exceptions, amendments and cross-references | A liability cap is separated from its exception |
| Slack | Thread, message group or coherent discussion segment | Root question, reply order, author/time and message references | A tentative suggestion is retrieved without the subsequent correction |
| Table-heavy PDF | Table, row group or cell with its coordinates | Header hierarchy, units, captions, footnotes and page positions | A number is detached from its metric, entity or reporting period |
A universal tokenizer and splitter can be a useful fallback and experimental baseline. It should not erase document structure before type-specific processing has had a chance to preserve it.
2. End-to-end ingestion architecture#
The shared pipeline handles source identity, parsing outcomes, stable evidence identifiers, tenant boundaries, permissions, versioning, indexing and query-time evidence assembly. The source-specific parser and chunker preserve the meaning of the original document. A quality gate prevents silently indexing malformed tables or incomplete documents as though they were reliable evidence.
An embedding model sees the serialized chunk, including any repeated context, so enforce its actual input limit after serialization. The generator has a separate context budget. Lexical indexing can additionally preserve exact clause numbers, error codes, names and other identifiers.
3. Contracts: preserve legal structure and dependencies#
Parsing#
Start from the original signed or otherwise authoritative version. Extract heading levels, articles, numbered sections, paragraphs, subclauses, schedules, exhibits and footnotes. For a scanned contract, use OCR and layout reconstruction, retain page coordinates and flag uncertain extraction for review.
Represent the document as a hierarchy. A clause such as 12.2(b) should have its parent section, title and exact location. Maintain links to defined terms and explicit references such as "subject to Section 14.3." Do not assume that text in a draft or unrelated agreement is applicable to the current contract.
Chunking#
Prefer a complete clause or subclause as the retrieval unit. A short definition can be a separate unit with a reference to the definitions section. A long section may need to be divided by its numbered subclauses or coherent paragraphs, retaining the section path in every child. If a single provision exceeds the model limit, split it at the best available semantic boundary and preserve the parent relationship; do not silently drop text.
For example, a fictional agreement contains:
- Section 8.1: liability is capped at fees paid over the preceding twelve months.
- Section 8.2: the cap does not apply to specified confidentiality breaches.
- Section 1: definitions of relevant terms.
Retrieving Section 8.1 alone is insufficient for an answer about confidentiality liability. Link the related exception and required definitions, and expand or perform a targeted second retrieval when the question requires them. Preserve original wording separately from any contextual prefix or generated summary. Never present a summary as verbatim contract text.
Metadata and retrieval#
Retain agreement ID, version, execution or effective dates where known, parties or matter IDs when permitted, section path, clause ID, page or character span, definition links, references, tenant and document permissions. Contract version and applicability are crucial: the most semantically similar clause from a different agreement may be legally irrelevant.
Use exact section lookup and lexical retrieval alongside embeddings. For high-stakes legal workflows, show the source text, include applicable exceptions and route unresolved interpretation to a qualified reviewer. Chunking cannot establish legal correctness on its own.
4. Slack: preserve conversational context, not just messages#
Parsing#
Use authorized exports or APIs, retaining workspace and channel identifiers, message IDs or timestamps, thread root and reply relationships, edits, deletions and available attachment references. Capture the source's actual access restrictions, including private channels, direct messages and externally shared conversations.
A Slack channel is not a single coherent document. Different conversations can be interleaved in chronological order, and a thread may span several days. Group threaded messages by their root identity rather than adjacency alone.
Chunking#
For short threads, keep the root question and replies together when the complete serialized thread fits. For long threads, split into coherent reply groups, retaining the root or an explicitly labeled concise context prefix. Preserve the original message IDs and chronological order. For unthreaded channel discussions, use conservative time windows, reply relationships and topic continuity, while marking uncertain groupings.
Suppose a fictional thread contains:
| Message | Content |
|---|---|
| Root | Can we release the migration on Friday? |
| Reply 1 | Friday looks possible. |
| Reply 2 | Security review is incomplete. |
| Reply 3 | Final decision: postpone until review passes. |
An arbitrary splitter might retrieve only the first reply and imply that Friday was approved. A thread-aware retrieval path can return the later decision and expand to the root and earlier discussion when necessary.
Avoid treating the last message as automatically authoritative. The latest reply may be a question or a tentative opinion. Distinguish decisions, proposals and unresolved discussion using source context and appropriate business authority.
Metadata and lifecycle#
Keep workspace, channel, root and message IDs, message timestamps, original message links, revision state, source spans, access policy references and attachment provenance. A user can lose access to a conversation after indexing. Recheck effective permissions at retrieval and parent expansion, and propagate edits, deletions and retention changes. Do not combine messages across access boundaries into a chunk that can be retrieved by users who cannot see all of them.
5. PDFs full of tables: preserve layout and cell semantics#
Parse before chunking#
PDF pages often encode positioned glyphs rather than logical rows and columns. Reading order, merged cells, multiple columns and tables that continue across pages may require layout-aware extraction. For native PDFs, inspect text coordinates and table boundaries. For scanned pages, use OCR with layout analysis. Extraction confidence is a diagnostic signal rather than proof of correctness.
Validate table headers, cell alignment, row counts, continuation pages and numeric values on representative samples. Retain the original page image or source reference for verification, subject to access controls. Flag uncertain merged-cell interpretation or unreadable values rather than inventing missing cells.
Table-aware representations#
For small tables, retain the whole table with its title, headers, units and footnotes. For larger tables, produce row-group chunks with repeated applicable headers and identifiers. For wide tables, group related columns while preserving row keys and all necessary header levels. Keep original cell coordinates so a result can be traced to the exact value.
Example fictional source table:
| Region | FY2025 revenue (USD millions) | FY2025 growth (%) |
|---|---|---|
| East | 100 | 5 |
| West | 200 | 8 |
If each row is a separate retrieval unit, include the header hierarchy and units in each chunk. "West 200 8" is insufficient: the values could refer to unrelated metrics or periods.
For tables spanning several pages, reconstruct the shared schema only when the continuation can be reliably identified. Preserve table ID, page ranges, row and column coordinates, caption, units and applicable footnotes. A superscript indicating a restated or estimated value can change the interpretation of an entire cell.
Exact numeric questions#
Embedding similarity is useful for locating a table but is not a reliable arithmetic engine. When a customer asks for totals, ratios, comparisons or filtered aggregates, retrieve the authorized table and use validated structured queries or deterministic calculations over typed values. Preserve currencies, units, null semantics and precision; do not let a model infer that a blank cell means zero. Cite the original cells or source rows used.
6. Parent-child retrieval and evidence assembly#
Index a relatively focused child chunk for precise retrieval. Store a link to its parent section, conversation or table. At query time, retrieve the child and selectively expand to surrounding context or linked evidence when the question requires it.
For contracts, expansion may involve the full clause plus a definition and an exception. For Slack, it may involve the root and later decision message. For tables, it may involve the relevant header, footnote and another row group.
Expansion is not a blanket rule to send entire documents to the generator. It increases token usage and can introduce irrelevant or restricted information. Recheck permissions on each expanded unit and validate that the additional context is applicable to the requested version and time period.
A generated contextual prefix or summary can help an embedding model understand a child chunk. Label derived text, retain source spans, and evaluate whether the prefix changes retrieval or introduces incorrect claims. Do not cite generated summaries as primary evidence.
7. A common chunk contract#
The shared schema should represent source identity without forcing every document into the same shape.
| Field | Purpose |
|---|---|
| chunk_id, source_id, source_version | Stable identity and reproducible retrieval |
| tenant_id, permission_policy_ref | Trusted access scope and revocation checks |
| source_type, parser_version, chunker_version | Route processing and reproduce results |
| text, context_prefix, representation_type | Distinguish original evidence from added context |
| parent_id, linked_evidence_ids | Targeted context expansion |
| source_spans | Page/character offsets, message IDs or table-cell coordinates |
| embedding_model_version, token_count | Compatibility and input-budget validation |
| updated_at, index_state, extraction_quality | Freshness, operational visibility and review |
| type_metadata | Clause path, thread root, table ID, header schema and related fields |
These are conceptual fields, not a prescribed database schema. Store trustworthy access metadata outside model control. Use stable source identifiers or deterministic versioned identifiers to support idempotent ingestion and prevent stale or duplicate chunks on retries. Avoid copying unnecessary sensitive metadata into model context.
8. Tested Python example: pack structured units without losing context#
This dependency-free implementation operates after source-specific parsing. It groups ordered atomic evidence units under a budget while repeating a required prefix in every chunk. A prefix can represent a section path, a thread root, or a table header. Each unit carries an identifier so the caller can preserve provenance.
PYTHONdef pack_units(units, prefix, budget, count): if budget <= 0 or count(prefix) > budget: raise ValueError('Invalid budget or oversized prefix') chunks, group = [], [] def render(group): return '\n'.join([prefix] + [text for _, text in group]) for uid, text in units: if count(render([(uid, text)])) > budget: raise ValueError(f'Oversized unit: {uid}') if group and count(render(group + [(uid, text)])) > budget: chunks.append((tuple(i for i, _ in group), render(group))) group = [] group.append((uid, text)) if group: chunks.append((tuple(i for i, _ in group), render(group))) return chunks
Example using character length as a deterministic test double, not an actual token counter:
PYTHONrows = [(1, 'East | 100'), (2, 'West | 200')] result = pack_units(rows, 'Region | Revenue (USD)', 34, len) print(result) # [((1,), 'Region | Revenue (USD)\nEast | 100'), # ((2,), 'Region | Revenue (USD)\nWest | 200')]
The function deliberately rejects an oversized individual unit instead of truncating it. Route such a unit to an appropriate source-specific subdivision strategy, or quarantine it when subdivision would destroy meaning. In production, inject the actual embedding model's tokenizer-based count function, include required model-specific formatting and special-token overhead, and validate the resulting serialized input. A counter may not be additive over substrings, so the helper counts the full rendered candidate instead of adding independent unit counts.
The helper assumes ordered input units, meaningful unique IDs within the source scope, a fixed prefix, a positive integer budget and a deterministic nonnegative count function. It neither parses files nor authorizes their contents. With n units, it makes O(n) count calls, but repeated serialization of a growing group can produce quadratic text-processing work in the worst case; production systems should profile and optimize without weakening the final full-input budget check.
Local verification: Executed the exact helper with 5,462 checks passing. This covered all unit-length combinations for zero through five units with lengths one through three, across fifteen budgets (5,460 cases), plus invalid-budget and oversized-prefix checks. Assertions checked source order, complete unit coverage, repeated prefix, maximum size, correct serialized text, greedy packing boundaries and rejection of oversized units. The explicit table example also ran successfully. The tests used a deterministic character-length counter and synthetic units; they do not validate a real model tokenizer, contract parser, Slack API, PDF extraction or semantic retrieval quality.
9. Evaluate chunking against the actual customer tasks#
Create a labeled dataset of queries with required evidence units defined at the source level, independent of a particular chunking configuration. Include contract clauses and exceptions, Slack decision threads, table headers and footnotes, continuation pages, ambiguous queries and inaccessible or nonexistent evidence.
Compare a fixed-window baseline with the document-aware approach and parent-child expansion. Keep the corpus snapshot, embedding model, access scope and final context budget comparable.
| Evaluation dimension | What to measure |
|---|---|
| Parsing fidelity | Clause boundaries, reply linkage, cell alignment and numeric extraction accuracy |
| Evidence Recall@k | Fraction of required source evidence retrieved |
| All-evidence success | Whether every required supporting unit is available |
| Final-context recall | Whether needed evidence survives reranking, expansion and token packing |
| Citation precision | Whether each citation points to the actual supporting clause, message or cell |
| Answer correctness | Accuracy against authoritative source evidence, including exceptions and units |
| Operational cost | Index size, embedding tokens, parsing time, retrieval latency and context cost |
| Security and freshness | Unauthorized exposure, deletion/revocation propagation and stale-version retrieval |
For a multi-source question, one relevant chunk is not enough if the answer also needs an exception or table footnote. Evaluate source-level evidence coverage rather than counting duplicate overlapping chunks as additional relevant evidence.
Inspect failures by document type. If table extraction is incorrect, changing the embedding model is unlikely to restore the lost structure. If the correct contract exception is indexed but not retrieved, investigate query formulation, metadata, cross-reference retrieval and ranking. If correct evidence reaches the generator but the response is wrong, inspect generation and validation.
Use customer-defined acceptance thresholds and separate critical failures from averages. Test access boundaries, especially when a returned child references a restricted parent. Evaluate real parsing and OCR accuracy with reviewed fixtures before enabling automated ingestion.
10. Production trade-offs#
| Decision | Trade-off and recommendation |
|---|---|
| Small versus large chunks | Small units improve precise retrieval but can lose context; large units retain context but consume more tokens and can dilute relevance |
| Overlap versus explicit links | Overlap is simple but duplicates text and increases indexing cost; links preserve structured dependencies but need reliable IDs and expansion logic |
| Shared versus specialized parser | A universal parser is easier to operate; specialized extraction improves fidelity for complex sources |
| Whole table versus row groups | Whole tables preserve global structure but may exceed limits; row groups need repeated headers, footnotes and stable coordinates |
| Raw text versus summaries | Summaries may improve coarse retrieval but risk omitting exceptions; keep original evidence for verification |
| Immediate versus asynchronous indexing | Fast updates improve freshness; queues and retries improve resilience but introduce synchronization lag |
Use bounded asynchronous processing, idempotent source-version jobs, error handling and a review queue for uncertain extractions. Cache expensive OCR or embeddings only when the source version and configuration match, and protect caches with the same access and retention requirements as the original data. Reindex changed units and affected dependencies when a document changes; for example, an updated table header may require regenerating every row-group representation.
Treat retrieved documents as untrusted data. Embedded instructions in a contract, Slack message or PDF do not grant tool permissions or override application policy. Enforce access before exposing evidence to rerankers or generators, and verify again before returning citations. Deletion and revocation must propagate through source stores, indexes, expanded context and caches.
Likely interviewer follow-ups#
Would you use a single chunk size? No. Set model-aware limits and tune retrieval granularity by document structure and actual task performance, rather than assume one size is optimal.
What if a contract clause refers to another clause? Preserve the reference and retrieve or expand to the applicable authorized target clause, including relevant definitions and exceptions.
How would you chunk an extremely long Slack thread? Segment ordered reply groups with root context and stable message IDs. Retrieve the relevant segment and expand selectively to associated decisions or corrections.
How do you avoid losing headers in a PDF table? Extract the header hierarchy and repeat the relevant labels, units and row identifiers in each indexed representation, with pointers to original cells.
Can embeddings answer financial questions directly? They can locate likely evidence. Use structured, validated computation for exact numerical answers.
How do you know the chunker is better? Compare source-level evidence recall, citation fidelity, complete answer quality, operational cost and security against a baseline on the same held-out customer tasks.
References
- 1.
- 2.pypdf — Extract Text from a PDF (not live-verified)pypdf.readthedocs.io
- 3.pdfplumber project (not live-verified)github.com
- 4.Docling project (not live-verified)github.com
- 5.
- 6.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models