-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf.go
More file actions
1968 lines (1850 loc) · 66.7 KB
/
Copy pathpdf.go
File metadata and controls
1968 lines (1850 loc) · 66.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package parser
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log/slog"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/hallelx2/pdftable"
pdflib "github.com/ledongthuc/pdf"
"github.com/pdfcpu/pdfcpu/pkg/api"
"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)
// PDF is a pragmatic first-pass PDF parser.
//
// PDF is a layout format, not a structured format — there are no real
// headings in the wire layer, just runs of glyphs with font sizes and
// positions. To recover structure we:
//
// 1. Extract positioned WORDS per page (font name + size + bbox) using
// pdftable's content-stream interpreter.
// 2. Compute the median font size across the whole document.
// 3. Treat any row whose font size exceeds a threshold (1.2× median)
// AND that is short (<= 14 words) as a heading candidate.
// 4. Group headings into levels by font-size buckets (largest = level 1).
// 5. Everything else is body text for the most recent heading.
// 6. Run pdftable's table-finding pipeline over each page and emit one
// extra Section per detected table whose Content is a GitHub-flavoured
// Markdown rendering of the cells. Tables are flagged with
// Metadata["table"]="true" so retrieval can lean on numeric content
// that would otherwise collapse into a space-joined run.
//
// Encrypted PDFs are auto-decrypted with the empty password via pdfcpu.
// PDFs with non-standard fonts and scanned PDFs (pure images) are not
// supported at this stage.
type PDF struct {
// Tables, when non-nil, overrides the default table-extraction
// behaviour (enabled, lines/lines strategies, minima 2×2). Pass nil
// to use the engine defaults; pass a zero value to disable tables
// entirely.
Tables *TableOpts
// MaxSections caps the number of leaf sections the parser emits for a
// single document. A pathological PDF — e.g. a 90-page filing whose
// every bold statement title and repeated "<Company> and
// Subsidiaries" line trips the heading detector, leaving a swarm of
// empty/tiny heading-only leaves — can otherwise produce far more
// leaves than the document has real sections. Each leaf later costs a
// summarize + HyDE LLM call, so an uncapped count directly throttles
// or stalls ingest.
//
// When the prose leaf count exceeds MaxSections, adjacent small leaf
// siblings under a shared parent are merged (smallest first) until the
// count is back under the cap. Table sections (which carry distinct
// numeric content) are never merged.
//
// Zero selects defaultMaxLeafSections. A negative value disables the
// cap entirely (escape hatch for callers that want the raw outline).
MaxSections int
// ParseTimeout bounds the ENTIRE Parse of one document — row
// extraction, table extraction, section building, and the leaf cap,
// end to end. It is the outermost robustness valve.
//
// Every other time bound inside the parser caps a sub-stage
// (tableExtractPageTimeout / tableExtractDocBudget cap table
// extraction), but the pure-Go row extractor
// (extractPDFRows -> reader.Page(n).Content()) had no bound at all —
// and that is exactly where a pathological PDF was observed hanging
// 600s+ in `parsing`, even in minimal mode (pre-LLM). ParseTimeout
// runs the whole parse on a goroutine and abandons it on deadline,
// returning a clear error so ingest fails the document fast instead
// of wedging forever.
//
// Nothing is disabled by this bound: when the parse finishes inside
// the deadline the full feature set (tables, the outline/heuristic
// section tree, the cap) is produced exactly as before.
//
// Zero selects defaultParseTimeout (120s). A non-positive value other
// than zero (i.e. negative) disables the bound entirely — Parse then
// runs synchronously with no deadline (escape hatch / legacy
// behaviour for callers that want an unbounded parse).
ParseTimeout time.Duration
}
// TableOpts controls pdftable's table-finding stage. The zero value
// disables table extraction; use DefaultTableOpts() for the
// production-default knobs.
type TableOpts struct {
// Enabled toggles table extraction. When false, the parser behaves
// exactly like the pre-integration text-only flow.
Enabled bool
// VerticalStrategy is forwarded to pdftable as
// TableSettings.VerticalStrategy. Empty falls back to "lines".
VerticalStrategy string
// HorizontalStrategy is forwarded to pdftable as
// TableSettings.HorizontalStrategy. Empty falls back to "lines".
HorizontalStrategy string
// MinTableRows is the minimum row count for a candidate table to be
// emitted as a Section. 0 means "no minimum"; recommend 2 in
// production so trivial single-row matches don't leak into the
// outline.
MinTableRows int
// MinTableCols is the minimum column count for a candidate table.
// Same semantics as MinTableRows.
MinTableCols int
}
// DefaultTableOpts returns the production defaults: tables on, both axes
// using the "lines" strategy, minima 2×2. These mirror pdftable's own
// DefaultTableSettings() and were tuned against the FinanceBench 10-K
// fixtures.
func DefaultTableOpts() *TableOpts {
return &TableOpts{
Enabled: true,
VerticalStrategy: "lines",
HorizontalStrategy: "lines",
MinTableRows: 2,
MinTableCols: 2,
}
}
// NewPDF returns a new PDF parser with table extraction enabled at the
// production defaults and the default leaf-section cap. Pass
// NewPDFWithTables(nil) (or a zero TableOpts) to opt out of tables.
func NewPDF() *PDF { return &PDF{Tables: DefaultTableOpts()} }
// NewPDFWithTables returns a PDF parser using the supplied table-
// extraction options and the default leaf-section cap. Pass nil to
// disable table extraction.
func NewPDFWithTables(opts *TableOpts) *PDF { return &PDF{Tables: opts} }
// NewPDFWithOpts returns a PDF parser using the supplied table-extraction
// options and an explicit leaf-section cap. maxSections == 0 selects
// defaultMaxLeafSections; a negative value disables the cap. The parse
// timeout is left at its zero value, which resolves to defaultParseTimeout.
func NewPDFWithOpts(opts *TableOpts, maxSections int) *PDF {
return &PDF{Tables: opts, MaxSections: maxSections}
}
// NewPDFWithConfig returns a PDF parser with the table options, leaf-
// section cap, AND total-parse timeout all set explicitly. This is the
// constructor the engine wiring uses so every parser robustness knob is
// operator-tunable via config (ingest.max_sections,
// ingest.parse_timeout_seconds).
//
// - maxSections == 0 → defaultMaxLeafSections; negative disables the cap.
// - parseTimeout == 0 → defaultParseTimeout; negative disables the bound.
func NewPDFWithConfig(opts *TableOpts, maxSections int, parseTimeout time.Duration) *PDF {
return &PDF{Tables: opts, MaxSections: maxSections, ParseTimeout: parseTimeout}
}
// Name implements Parser.
func (*PDF) Name() string { return "pdf" }
// Accepts implements Parser.
func (*PDF) Accepts(contentType, filename string) bool {
if contentType == "application/pdf" {
return true
}
return HasExt(filename, ".pdf")
}
// Parse implements Parser.
//
// Parse is a thin timeout wrapper around the real parse work (parseDoc).
// It bounds the WHOLE parse — row extraction, table extraction, section
// building, and the leaf cap — by p.resolvedParseTimeout(). The work runs
// on a goroutine; if it doesn't finish by the deadline (or ctx is
// cancelled) Parse returns a clear error and abandons the goroutine. The
// goroutine then finishes on its own (or is GC'd) — its result lands in a
// buffered channel so it never blocks on send. This is the same
// abandon-on-deadline pattern safeExtractTables already uses for a single
// table page, lifted to cover the entire parse so ANY parse pathology
// (notably the unbounded pure-Go ledongthuc row extractor) fails fast and
// cleanly instead of hanging ingest forever.
//
// A negative ParseTimeout disables the bound and runs parseDoc inline.
func (p *PDF) Parse(ctx context.Context, r io.Reader) (*ParsedDoc, error) {
// Read the bytes up front (outside the deadline goroutine): io.ReadAll
// is bounded by the reader/storage layer, not by the PDF pathology we
// are guarding against, and reading here keeps the goroutine body a
// pure CPU/parse unit.
buf, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return runParseWithDeadline(ctx, p.resolvedParseTimeout(), func() (*ParsedDoc, error) {
return p.parseDoc(ctx, buf)
})
}
// runParseWithDeadline runs work bounded by timeout. It is the reusable
// core of the whole-Parse robustness valve, factored out so the
// deadline/abandon mechanism is unit-testable with an arbitrary work
// closure (e.g. one that sleeps past the deadline) without needing a
// pathological real PDF.
//
// - timeout <= 0 runs work inline with NO bound (legacy/unbounded
// behaviour; the explicit escape hatch a negative ParseTimeout selects).
// - Otherwise work runs on a goroutine and the function selects on the
// work result, a time.After(timeout), and ctx cancellation. On
// timeout/cancel the goroutine is abandoned: its result lands in a
// buffered channel so it can always send and exit (no leak on send),
// then runs to completion on its own and is collected. A panic inside
// work is recovered and surfaced as an error so a backend bug can
// never crash the ingest worker.
//
// The timeout/cancel errors are deliberately phrased so the ingest
// pipeline's existing "parse failed → document failed" path produces a
// clear, ops-visible message instead of an infinite hang.
func runParseWithDeadline(ctx context.Context, timeout time.Duration, work func() (*ParsedDoc, error)) (*ParsedDoc, error) {
if timeout <= 0 {
return work()
}
type result struct {
doc *ParsedDoc
err error
}
done := make(chan result, 1)
go func() {
defer func() {
if rec := recover(); rec != nil {
done <- result{err: fmt.Errorf("pdf: parse panicked: %v", rec)}
}
}()
doc, perr := work()
done <- result{doc: doc, err: perr}
}()
select {
case res := <-done:
return res.doc, res.err
case <-time.After(timeout):
return nil, fmt.Errorf("pdf: parse exceeded %s — document too complex or malformed", timeout)
case <-ctx.Done():
return nil, fmt.Errorf("pdf: parse cancelled: %w", ctx.Err())
}
}
// pdftableOpenMu serializes pdftable.OpenBytes. pdftable mutates package-level
// state while opening a document and is not safe for concurrent callers — the
// race detector flags concurrent OpenBytes calls, and this is real in
// production because ingest workers parse documents in parallel. Serializing
// just the open (the only racing call) keeps correctness at a small cost.
// Stopgap: the proper fix is to make pdftable itself concurrency-safe
// (tracked in the Foundational Libraries project).
var pdftableOpenMu sync.Mutex
// openPDFBytes is the concurrency-safe wrapper around pdftable.OpenBytes.
func openPDFBytes(b []byte) (pdftable.Document, error) {
pdftableOpenMu.Lock()
defer pdftableOpenMu.Unlock()
return pdftable.OpenBytes(b)
}
// parseDoc is the real parse implementation. It is bounded by Parse's
// deadline wrapper; on its own it has no time bound beyond the per-stage
// table-extraction budgets.
func (p *PDF) parseDoc(_ context.Context, buf []byte) (*ParsedDoc, error) {
// We run TWO PDF backends in parallel here:
//
// - pdftable (the new primitive layer) extracts positioned WORDS
// (font name + size + bbox) directly. This is the input to the
// section-discovery heuristics and is also the only source for
// the table-finding pass. It is robust to letter-spaced glyphs
// and ships pdfplumber-parity word grouping out of the box.
//
// - ledongthuc/pdf is retained solely for /Outlines (bookmark)
// access — pdftable does not expose the outline dictionary yet,
// and outlines are ground truth for SEC filings / academic papers
// that have one. Once pdftable surfaces outlines we can drop the
// dependency entirely.
//
// Both backends consume the same byte slice. If pdftable rejects the
// document as encrypted we strip the encryption layer with pdfcpu
// (empty password) and retry — this is the path that lets us index
// "owner-password" PDFs whose only restriction is print/copy.
docBytes := buf
pdoc, err := openPDFBytes(docBytes)
if err != nil {
if isPdftableEncryptedErr(err) {
cleaned, decErr := decryptPDFWithEmptyPassword(buf)
if decErr != nil {
return nil, fmt.Errorf("pdf: open: encrypted and could not be unlocked with empty password: %w", decErr)
}
docBytes = cleaned
pdoc, err = openPDFBytes(docBytes)
}
if err != nil {
return nil, fmt.Errorf("pdf: open: %w", err)
}
}
defer func() { _ = pdoc.Close() }() // best-effort close
// ledongthuc/pdf is now used ONLY for /Outlines (bookmarks). Text and
// rows come from pdftable's Words() (v0.4.0: correct order + spacing).
// A reader failure is therefore non-fatal — we just lose the outline
// hint and fall back to the font-size heuristic on the pdftable rows.
reader, rerr := pdflib.NewReader(bytes.NewReader(docBytes), int64(len(docBytes)))
if rerr != nil {
reader = nil
}
rows, err := extractPDFRows(pdoc)
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, fmt.Errorf("pdf: parsed but no extractable text — the document may be a scanned image (OCR not yet supported) or use a font encoding the parser can't read")
}
// Sanity check on extracted content. PDFs with overlay watermarks
// drawn on top of every page (the GINA-style "DO NOT COPY..." kind)
// can produce rows that are mostly noise — extracted text consists
// of doubled glyphs from the two layers being interleaved by Y.
// Bail with a clear message instead of going "ready" on empty data.
if !rowsLookLikeUsableText(rows) {
return nil, fmt.Errorf("pdf: text extraction produced no usable content — the document may have an overlay watermark or use a non-standard font encoding")
}
// Run table extraction once, BEFORE we commit to either the outline
// path or the heuristic path: both should be able to inherit the
// same set of detected tables.
tableSections := extractPDFTables(pdoc, p.Tables)
// If the PDF ships with a real outline (bookmarks), use it as ground
// truth for structure — beats any font-size heuristic. We still rely
// on row extraction for section bodies by matching outline titles
// against the first occurrence of that text in the row stream.
if reader != nil {
if outline := reader.Outline(); len(outline.Child) > 0 {
if doc, ok := parsePDFWithOutline(outline, rows); ok {
doc.Sections = capLeafSections(doc.Sections, p.resolvedMaxSections())
attachTableSections(doc, tableSections)
return doc, nil
}
}
}
// Median font size — our reference for "normal body text".
sizes := make([]float64, 0, len(rows))
for _, r := range rows {
if r.fontSize > 0 {
sizes = append(sizes, r.fontSize)
}
}
sort.Float64s(sizes)
median := 0.0
if n := len(sizes); n > 0 {
median = sizes[n/2]
}
headingFloor := median * 1.2
// Unique heading sizes, largest first. These define heading levels:
// the largest bucket is level 1, next is level 2, etc. (capped at 6).
levelForSize := buildHeadingLevelMap(rows, headingFloor)
// Bold rows at (at least) body size are headings too. Filings bold their
// section headers rather than enlarging them, so a size-only heuristic
// collapses the whole body into one block. Bold-derived headings nest one
// level below the smallest font-derived heading level.
boldLevel := 1
for _, lv := range levelForSize {
if lv+1 > boldLevel {
boldLevel = lv + 1
}
}
if boldLevel > 6 {
boldLevel = 6
}
type flat struct {
level int
title string
body strings.Builder
pageStart int // min source page touched by this flat (0 = none seen yet)
pageEnd int // max source page touched by this flat
}
flats := []*flat{{level: 0, title: ""}}
current := flats[0]
// touch records that this flat consumed a row from the given page,
// expanding pageStart/pageEnd. Pages on rows that aren't body text
// (e.g. a heading row itself) are also counted: the heading lives on
// that page, so the section visibly starts there.
touch := func(f *flat, page int) {
if page <= 0 {
return
}
if f.pageStart == 0 || page < f.pageStart {
f.pageStart = page
}
if page > f.pageEnd {
f.pageEnd = page
}
}
for _, row := range rows {
text := strings.TrimSpace(row.text)
if text == "" {
continue
}
lvl, isHeading := levelForSize[roundSize(row.fontSize)]
if !isHeading && row.bold && row.fontSize >= median && looksLikeHeading(text) {
isHeading = true
lvl = boldLevel
}
if isHeading && looksLikeHeading(text) {
// A *sub-numbered* prefix ("3.1", "3.1.2") signals extra nesting
// depth relative to the font-derived level. We only ever DEEPEN
// (never change the base level), so top-level headings — numbered
// "3" or not ("Abstract") — stay siblings at the same font level.
newLevel := lvl
if nd, ok := numberedHeadingDepth(text); ok && nd > 1 {
newLevel += nd - 1
}
// Multi-line display heading: a run of heading rows at the SAME
// level, on the SAME page, with NO body text accrued between them
// is one visual heading wrapped across lines — e.g. a hero title
// "THE SYSTEM, END-TO-END" / "How Vectorless" / "actually works."
// Left un-merged, each line becomes its own heading flat whose
// body is empty, shipping as a "purely structural" Section that
// returns empty content to the section browser / API. Fold the
// continuation line into the current heading instead so the body
// that follows attaches to the whole title and no empty fragment
// section is emitted. We only merge when the current flat is
// itself an as-yet-empty heading at the same level on the same
// page — never across a level change (real nesting) or once body
// text has begun.
if current.level > 0 && newLevel == current.level &&
current.title != "" &&
strings.TrimSpace(current.body.String()) == "" &&
(current.pageEnd == 0 || row.page == 0 || row.page == current.pageEnd) {
current.title = strings.TrimSpace(current.title + " " + text)
touch(current, row.page)
continue
}
current = &flat{level: newLevel, title: text}
touch(current, row.page)
flats = append(flats, current)
continue
}
if current.body.Len() > 0 {
current.body.WriteString(" ")
}
current.body.WriteString(text)
touch(current, row.page)
}
if len(flats) > 1 && flats[0].level == 0 && strings.TrimSpace(flats[0].body.String()) == "" {
flats = flats[1:]
}
var title string
for _, f := range flats {
if f.level == 1 {
title = f.title
break
}
}
if title == "" && len(flats) > 0 {
title = flats[0].title
}
// Build hierarchy via level stack.
rootSec := &Section{Level: 0, Title: title}
stack := []*Section{rootSec}
for _, f := range flats {
sec := Section{
Level: f.level,
Title: f.title,
Content: strings.TrimSpace(f.body.String()),
PageStart: f.pageStart,
PageEnd: f.pageEnd,
}
if f.level == 0 {
if sec.Content == "" {
continue
}
sec.Level = 1
sec.Title = "Introduction"
}
for len(stack) > 1 && stack[len(stack)-1].Level >= sec.Level {
stack = stack[:len(stack)-1]
}
parent := stack[len(stack)-1]
parent.Children = append(parent.Children, sec)
tail := &parent.Children[len(parent.Children)-1]
stack = append(stack, tail)
}
// No headings recovered? Fall back to one "Document" section spanning
// every page we saw.
if len(rootSec.Children) == 0 {
var all strings.Builder
minPage, maxPage := 0, 0
for _, f := range flats {
if s := strings.TrimSpace(f.body.String()); s != "" {
if all.Len() > 0 {
all.WriteString(" ")
}
all.WriteString(s)
}
if f.pageStart > 0 && (minPage == 0 || f.pageStart < minPage) {
minPage = f.pageStart
}
if f.pageEnd > maxPage {
maxPage = f.pageEnd
}
}
rootSec.Children = []Section{{
Level: 1,
Title: "Document",
Content: all.String(),
PageStart: minPage,
PageEnd: maxPage,
}}
}
// Drop empty "structural" leaf fragments (multi-line title remnants,
// running headers) so no section returns empty content to the browser /
// API; their titles ride onto the sibling body they head.
rootSec.Children = foldEmptyLeafSections(rootSec.Children)
// Internal sections inherit the union of their children's page ranges
// so callers reading the outline can still cite a page span.
propagateSectionPages(rootSec.Children)
out := &ParsedDoc{
Title: title,
Sections: capLeafSections(chunkOversizedLeaves(rootSec.Children), p.resolvedMaxSections()),
}
attachTableSections(out, tableSections)
return out, nil
}
// resolvedMaxSections turns the configured MaxSections into the value
// the cap actually uses: 0 selects defaultMaxLeafSections; a negative
// value disables the cap (returns a non-positive number capLeafSections
// treats as "off").
func (p *PDF) resolvedMaxSections() int {
if p.MaxSections == 0 {
return defaultMaxLeafSections
}
return p.MaxSections
}
// defaultParseTimeout is the whole-Parse deadline applied when
// ParseTimeout is left at its zero value. 120s is comfortably longer than
// a healthy 300-page filing's parse (seconds to low tens of seconds) yet
// short enough that a pathological/malformed document — the kind observed
// hanging 600s+ in pure-Go row extraction — is reaped quickly and the
// document fails fast instead of wedging ingest.
const defaultParseTimeout = 120 * time.Second
// resolvedParseTimeout turns the configured ParseTimeout into the value
// the wrapper actually uses: 0 selects defaultParseTimeout; a negative
// value disables the bound (Parse runs parseDoc inline with no deadline).
func (p *PDF) resolvedParseTimeout() time.Duration {
if p.ParseTimeout == 0 {
return defaultParseTimeout
}
return p.ParseTimeout
}
// foldEmptyLeafSections eliminates leaf sections (no children) whose
// content is empty. A PDF whose heading detector fires on a fragment that
// carries no body — a lone display-title line the row-merge didn't catch,
// a repeated running header, a stray bold word — otherwise ships as a
// "purely structural" Section that returns empty content to the section
// browser and the /v1/sections/{id} API, which reads as a broken/empty
// part of the document.
//
// The fold is lossless: an empty leaf's TITLE is preserved by attaching it
// as a bold markdown heading line to the content of the sibling it heads —
// the NEXT sibling when one exists (the body it introduces), else the
// PREVIOUS sibling. Consecutive empty leaves accumulate and flush together
// into the first sibling that can carry them, so a multi-line title that
// escaped the row-merge still lands as one heading block above its body.
// Page ranges union so citations stay correct. Internal nodes (sections
// WITH children) are recursed into but never dropped — an empty heading
// with real sub-sections is legitimate structure whose content lives in
// its children.
//
// A lone empty leaf with no siblings to carry its title is kept as-is
// (dropping it would erase the only trace of that heading); this is the
// rare degenerate case and harms nothing.
func foldEmptyLeafSections(sections []Section) []Section {
for i := range sections {
if len(sections[i].Children) > 0 {
sections[i].Children = foldEmptyLeafSections(sections[i].Children)
}
}
// Collect the indices of empty leaves eligible to fold. A section is an
// empty leaf when it has no children and no non-whitespace content.
emptyLeaf := func(s *Section) bool {
return len(s.Children) == 0 && strings.TrimSpace(s.Content) == ""
}
// Nothing to do unless there is at least one empty leaf AND at least one
// sibling that can carry a folded title.
empties, carriers := 0, 0
for i := range sections {
if emptyLeaf(§ions[i]) {
empties++
} else {
carriers++
}
}
if empties == 0 || carriers == 0 {
return sections
}
out := make([]Section, 0, len(sections))
var pendingTitles []string
var pendStart, pendEnd int
takePending := func(target *Section) {
if len(pendingTitles) == 0 {
return
}
var b strings.Builder
for _, t := range pendingTitles {
b.WriteString("**")
b.WriteString(t)
b.WriteString("**\n\n")
}
b.WriteString(target.Content)
target.Content = strings.TrimSpace(b.String())
target.PageStart = minNonZero(pendStart, target.PageStart)
if pendEnd > target.PageEnd {
target.PageEnd = pendEnd
}
pendingTitles = nil
pendStart, pendEnd = 0, 0
}
for i := range sections {
s := sections[i]
if emptyLeaf(&s) {
if t := strings.TrimSpace(s.Title); t != "" {
pendingTitles = append(pendingTitles, t)
pendStart = minNonZero(pendStart, s.PageStart)
if s.PageEnd > pendEnd {
pendEnd = s.PageEnd
}
}
continue // drop the empty leaf; its title rides on pendingTitles
}
// A real section: it carries any pending titles as heading prefix
// (these are the fragments it follows).
takePending(&s)
out = append(out, s)
}
// Any titles still pending had no following carrier — attach them to the
// last emitted sibling as a trailing heading block so nothing is lost.
if len(pendingTitles) > 0 && len(out) > 0 {
last := &out[len(out)-1]
var b strings.Builder
b.WriteString(last.Content)
for _, t := range pendingTitles {
b.WriteString("\n\n**")
b.WriteString(t)
b.WriteString("**")
}
last.Content = strings.TrimSpace(b.String())
if pendEnd > last.PageEnd {
last.PageEnd = pendEnd
}
last.PageStart = minNonZero(pendStart, last.PageStart)
}
return out
}
// propagateSectionPages fills internal-node PageStart/PageEnd from the union
// of descendant leaf ranges where the internal node didn't have its own
// (because its body was empty / hoisted into children). Leaves keep their
// own range untouched.
func propagateSectionPages(sections []Section) (minPage, maxPage int) {
for i := range sections {
s := §ions[i]
childMin, childMax := propagateSectionPages(s.Children)
// Fold the section's own range with its children's.
if s.PageStart > 0 && (childMin == 0 || s.PageStart < childMin) {
childMin = s.PageStart
}
if s.PageEnd > childMax {
childMax = s.PageEnd
}
// Only widen the section — never shrink a populated range to 0.
if childMin > 0 {
s.PageStart = childMin
}
if childMax > 0 {
s.PageEnd = childMax
}
if s.PageStart > 0 && (minPage == 0 || s.PageStart < minPage) {
minPage = s.PageStart
}
if s.PageEnd > maxPage {
maxPage = s.PageEnd
}
}
return minPage, maxPage
}
// Filing cover pages (and any other long, mixed-topic leaf) often produce one
// 2-3k-char section under a generic title like "3M COMPANY", which mixes
// registration tables, addresses, IRS IDs and contact info. A single summary
// can't cover all those topics, so retrieval misses. Split such leaves into
// smaller sub-sections at word boundaries; each sub-section then gets its own
// title (from a natural colon-terminated header, e.g. "Securities registered
// pursuant to Section 12(b) of the Act", or the first few words) and its own
// summary downstream.
const (
leafChunkThreshold = 2400 // chars; high enough to leave paper sub-sections alone
leafChunkTarget = 900 // chars per chunk, give or take
)
// defaultMaxLeafSections is the ceiling NewPDF applies when MaxSections
// is left at zero. A 92-page 10-K whose "Notes to Financial Statements"
// section byte-splits into ~50 chunks (and whose body splits into
// hundreds more) was observed producing ~1500 leaves — each one of
// which then costs a summarize + HyDE + multi-axis LLM call at ingest,
// which is what stalled the pipeline. 400 keeps a filing richly
// structured while bounding ingest cost to something Gemini's
// free-tier RPM can clear.
const defaultMaxLeafSections = 400
// countLeafSections returns the number of leaf sections (no children)
// in the tree rooted at sections.
func countLeafSections(sections []Section) int {
n := 0
for i := range sections {
if len(sections[i].Children) == 0 {
n++
} else {
n += countLeafSections(sections[i].Children)
}
}
return n
}
// capLeafSections enforces a ceiling on the total leaf-section count so a
// pathological PDF can't shatter into thousands of tiny leaves (each of
// which costs a summarize + HyDE + multi-axis LLM call at ingest, which
// is what throttles/stalls the full pipeline). maxLeaves <= 0 disables
// the cap; a tree already at or under the cap is returned untouched.
//
// The reduction is robust to ANY tree shape, which is the fix for the
// real 10-K explosion: that document is not a flat list of adjacent
// leaves but hundreds of SINGLE-LEAF PARENTS (heading -> one body leaf),
// which have no adjacent leaf-sibling pairs at all — so the old
// adjacent-only merge silently did nothing and a 92-page filing sailed
// past the cap at 463-1465 leaves. We fix it in two phases:
//
// 1. collapseSingleLeafParents flattens every heading -> lone-leaf chain
// so the formerly-only-children become adjacent leaf SIBLINGS. This
// restructures the tree without changing the leaf count (the parent
// absorbs the child and itself becomes the leaf).
//
// 2. The merge loop then repeatedly merges the smallest adjacent leaf
// pair until the count is back under the cap (a defensive collapse
// step covers any pair a table leaf blocked).
//
// The invariant: for any tree with > maxLeaves MERGEABLE leaves,
// capLeafSections drives countLeafSections to <= maxLeaves. The only
// leaves it will not merge are table sections (Metadata["table"]=="true")
// — those carry distinct numeric content and must survive verbatim. In
// the normal parse flow table sections are attached AFTER this pass
// (attachTableSections), so the cap never sees them; the guard is
// defensive for any caller that pre-attaches tables.
//
// Merged/collapsed leaves concatenate their content (blank-line
// separated), keep the parent/first-sibling title, and union their page
// ranges, so no body text is ever dropped.
func capLeafSections(sections []Section, maxLeaves int) []Section {
if maxLeaves <= 0 {
return sections
}
if countLeafSections(sections) <= maxLeaves {
return sections // already under the cap — leave structure untouched
}
// Wrap the top-level sections under a synthetic root. The merge step
// shrinks a sibling list in place (it rewrites parent.Children), which
// only propagates back to the caller when the mutated list is a struct
// FIELD, not a bare slice parameter. The runaway shape we're fixing —
// hundreds of single-leaf PARENTS — needs the TOP-level list to shrink,
// so we make the top level a nested list (root.Children) and operate on
// that; the wrapper itself (length 1) never changes. We return
// root.Children at the end.
root := []Section{{Children: sections}}
// Phase 1: flatten single-leaf-parent chains so only-children become
// mergeable siblings. Count is unchanged; structure is normalised.
root[0].Children = collapseSingleLeafParents(root[0].Children)
// Phase 2: merge adjacent leaf pairs (smallest first) until under cap.
// Each merge removes one leaf and each fallback collapse removes one
// internal node — both strictly monotonic — so the loop is bounded;
// the guard is belt-and-braces against a logic regression.
for guard := 0; countLeafSections(root) > maxLeaves && guard < 1000000; guard++ {
if mergeOneSmallestAdjacentLeafPair(root) {
continue
}
// No adjacent mergeable pair left. Try to free one up by
// collapsing a remaining single-leaf parent; if that's impossible
// too, every remaining leaf is unmergeable (e.g. table sections)
// and we stop — there is nothing left we're permitted to merge.
if !collapseOneSingleLeafParent(&root) {
break
}
}
return root[0].Children
}
// isTableLeaf reports whether s is a table section that must never be
// merged or collapsed (its cell content is distinct numeric data).
func isTableLeaf(s *Section) bool {
return s.Metadata != nil && s.Metadata["table"] == "true"
}
// collapseSingleLeafParents recursively flattens every parent that has
// exactly one child which is a (non-table) leaf: the parent absorbs the
// child's content + page range and itself becomes the leaf. Chains
// (heading -> subheading -> body) collapse fully in one bottom-up pass.
//
// Leaf count is preserved (one internal node + one leaf become one leaf);
// the point is purely to turn only-children into adjacent siblings so the
// adjacent-pair merge can then reduce the count. Returns the rewritten
// slice.
func collapseSingleLeafParents(sections []Section) []Section {
for i := range sections {
s := §ions[i]
if len(s.Children) == 0 {
continue
}
// Bottom-up: collapse within the children first so a chain folds
// from the leaf upward.
s.Children = collapseSingleLeafParents(s.Children)
if len(s.Children) == 1 && len(s.Children[0].Children) == 0 && !isTableLeaf(&s.Children[0]) {
absorbChildIntoParent(s, s.Children[0])
s.Children = nil
}
}
return sections
}
// collapseOneSingleLeafParent finds the first parent in the tree with
// exactly one (non-table) leaf child and collapses it (parent absorbs the
// leaf, becomes a leaf). Returns false when no such parent exists. Used
// as a defensive fallback inside the merge loop when an adjacent pair was
// blocked by a table leaf; the bulk flattening is done up front by
// collapseSingleLeafParents.
func collapseOneSingleLeafParent(sections *[]Section) bool {
s := *sections
for i := range s {
n := &s[i]
if len(n.Children) == 1 && len(n.Children[0].Children) == 0 && !isTableLeaf(&n.Children[0]) {
absorbChildIntoParent(n, n.Children[0])
n.Children = nil
return true
}
if len(n.Children) > 0 {
if collapseOneSingleLeafParent(&n.Children) {
return true
}
}
}
return false
}
// absorbChildIntoParent folds a leaf child's content and page range up
// into its parent. The parent keeps its own title (the heading) and
// gains the child's body; an empty parent body is replaced outright so we
// don't prefix a stray separator. Page ranges union (min start, max end).
func absorbChildIntoParent(parent *Section, child Section) {
switch {
case strings.TrimSpace(parent.Content) == "":
parent.Content = child.Content
case strings.TrimSpace(child.Content) != "":
parent.Content = parent.Content + "\n\n" + child.Content
}
parent.PageStart = minNonZero(parent.PageStart, child.PageStart)
if child.PageEnd > parent.PageEnd {
parent.PageEnd = child.PageEnd
}
}
// mergeOneSmallestAdjacentLeafPair finds the adjacent leaf-sibling pair
// with the smallest combined content length anywhere in the tree and
// merges it in place. Only pairs where BOTH siblings are NON-table leaves
// are eligible — table sections are never merged. Returns false when no
// sibling list has two adjacent mergeable leaves.
func mergeOneSmallestAdjacentLeafPair(sections []Section) bool {
bestList := (*[]Section)(nil)
bestIdx := -1
bestSize := -1
var walk func(list *[]Section)
walk = func(list *[]Section) {
s := *list
for i := 0; i+1 < len(s); i++ {
if len(s[i].Children) == 0 && len(s[i+1].Children) == 0 &&
!isTableLeaf(&s[i]) && !isTableLeaf(&s[i+1]) {
size := len(s[i].Content) + len(s[i+1].Content)
if bestSize < 0 || size < bestSize {
bestSize, bestList, bestIdx = size, list, i
}
}
}
for i := range s {
if len(s[i].Children) > 0 {
walk(&s[i].Children)
}
}
}
walk(§ions)
if bestList == nil {
return false
}
s := *bestList
a, b := s[bestIdx], s[bestIdx+1]
merged := a
if strings.TrimSpace(a.Content) == "" {
merged.Content = b.Content
} else if strings.TrimSpace(b.Content) != "" {
merged.Content = a.Content + "\n\n" + b.Content
}
merged.PageStart = minNonZero(a.PageStart, b.PageStart)
if b.PageEnd > merged.PageEnd {
merged.PageEnd = b.PageEnd
}
s[bestIdx] = merged
*bestList = append(s[:bestIdx+1], s[bestIdx+2:]...)
return true
}
// minNonZero returns the smaller of two page numbers, treating 0
// (unknown) as "no lower bound" so a known page always wins.
func minNonZero(a, b int) int {
switch {
case a == 0:
return b
case b == 0:
return a
case a < b:
return a
default:
return b
}
}
// chunkOversizedLeaves splits any LEAF section whose content exceeds
// leafChunkThreshold into smaller sub-sections. Internal nodes (sections with
// children) are recursed into but never split — they're already structured.
func chunkOversizedLeaves(sections []Section) []Section {
out := make([]Section, 0, len(sections))
for _, s := range sections {
if len(s.Children) > 0 {
s.Children = chunkOversizedLeaves(s.Children)
out = append(out, s)
continue
}
if len(s.Content) <= leafChunkThreshold {
out = append(out, s)
continue
}
pieces := splitContentByWords(s.Content, leafChunkTarget)
if len(pieces) <= 1 {
out = append(out, s)
continue
}
parent := Section{Level: s.Level, Title: s.Title, PageStart: s.PageStart, PageEnd: s.PageEnd}
for i, piece := range pieces {
fallback := fmt.Sprintf("%s — part %d", s.Title, i+1)
// We don't track per-chunk pages once content is byte-split — each
// chunk inherits the parent's range (the leaf is the same source
// material). Good-enough for retrieval citations.
parent.Children = append(parent.Children, Section{
Level: s.Level + 1,
Title: deriveChunkTitle(piece, fallback),
Content: piece,
PageStart: s.PageStart,