Skip to content
6 changes: 5 additions & 1 deletion acceleration/internal/api/documents.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,11 @@ func documentFailure(err error) error {
}
switch reason {
case extract.TooLarge:
return documentTooLarge(fmt.Sprintf("the file is larger than a file sent with a question may be (at most %d pages): %v", maxDocumentPages, err))
var pages extract.PageLimit
if errors.As(err, &pages) {
return documentTooLarge(fmt.Sprintf("the file is larger than a file sent with a question may be (at most %d pages): %v", maxDocumentPages, err))
}
return documentTooLarge(fmt.Sprintf("the file is too large or too deeply nested for a file sent with a question: %v", err))
case extract.Unsupported:
return newAPIError(ErrorTypeUnsupportedMediaType, "the file is no format that can be read: a PDF or a Word document (DOCX or DOC) can be sent")
case extract.Encrypted:
Expand Down
85 changes: 85 additions & 0 deletions acceleration/internal/api/documents_unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package api

import (
"archive/zip"
"bytes"
"context"
"os"
"strings"
"testing"

"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/knowledge/extract"
)

// DocumentFailureSuite covers how a refused file is answered to the person who sent it.
type DocumentFailureSuite struct {
suite.Suite
}

func TestDocumentFailureSuite(t *testing.T) {
suite.Run(t, new(DocumentFailureSuite))
}

// Defect: every too-large refusal said the file had too many pages, so a Word file refused for its
// nesting told the sender to cut pages that were not the problem.
func (s *DocumentFailureSuite) TestAFileRefusedForItsNestingIsNotToldItHasTooManyPages() {
var archive bytes.Buffer
writer := zip.NewWriter(&archive)
part, err := writer.Create("word/document.xml")
s.Require().NoError(err)
_, err = part.Write([]byte(`<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>` +
strings.Repeat("<x>", 1<<12) + strings.Repeat("</x>", 1<<12) + `</w:body></w:document>`))
s.Require().NoError(err)
s.Require().NoError(writer.Close())
_, err = NewDocumentReader(extract.Options{}).Extract(context.Background(), "a.docx", archive.Bytes())
s.Require().Error(err)

failure := documentFailure(err)

var refused APIError
s.Require().ErrorAs(failure, &refused)
s.Equal(codeDocumentTooLarge, refused.Code)
s.Contains(refused.Message, "nested")
s.NotContains(refused.Message, "pages")
}

func (s *DocumentFailureSuite) TestAFileOverThePageLimitIsToldHowManyPagesAreRead() {
Comment thread
kanat marked this conversation as resolved.
Resolved
data, err := os.ReadFile("../knowledge/extract/testdata/manual.pdf")
s.Require().NoError(err)
_, err = extract.New(extract.Options{MaxPages: 1}).Extract(context.Background(), "manual.pdf", data)
s.Require().Error(err)

failure := documentFailure(err)

var refused APIError
s.Require().ErrorAs(failure, &refused)
s.Equal(codeDocumentTooLarge, refused.Code)
s.Contains(refused.Message, "(at most 100 pages)")
}

// Defect: a Word file with more pages than the limit was refused by the generic too-large wording,
// so the sender was not told how many pages are read.
func (s *DocumentFailureSuite) TestAWordFileOverThePageLimitIsToldHowManyPagesAreRead() {
var archive bytes.Buffer
writer := zip.NewWriter(&archive)
part, err := writer.Create("word/document.xml")
s.Require().NoError(err)
_, err = part.Write([]byte(`<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>` +
`<w:p><w:r><w:t>one</w:t></w:r></w:p>` +
`<w:p><w:r><w:lastRenderedPageBreak/><w:t>two</w:t></w:r></w:p>` +
`<w:p><w:r><w:lastRenderedPageBreak/><w:t>three</w:t></w:r></w:p>` +
`</w:body></w:document>`))
s.Require().NoError(err)
s.Require().NoError(writer.Close())
_, err = extract.New(extract.Options{MaxPages: 1}).Extract(context.Background(), "a.docx", archive.Bytes())
s.Require().Error(err)

failure := documentFailure(err)

var refused APIError
s.Require().ErrorAs(failure, &refused)
s.Equal(codeDocumentTooLarge, refused.Code)
s.Contains(refused.Message, "(at most 100 pages)")
}
14 changes: 7 additions & 7 deletions acceleration/internal/knowledge/extract/docx.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ func wordImages(data []byte) (map[string]string, error) {
if data == nil {
return images, nil
}
decoder := xml.NewDecoder(bytes.NewReader(data))
decoder := newDocumentDecoder(data)
for {
token, err := decoder.Token()
if errors.Is(err, io.EOF) {
return images, nil
}
if err != nil {
return nil, fail(Corrupt, DOCX, fmt.Errorf("document.xml.rels: %w", err))
return nil, xmlFailure(DOCX, fmt.Errorf("document.xml.rels: %w", err))
}
element, ok := token.(xml.StartElement)
if !ok || element.Name.Local != "Relationship" || attr(element, "TargetMode") == "External" ||
Expand All @@ -109,7 +109,7 @@ func wordStyles(data []byte) (map[string]wordStyle, error) {
if data == nil {
return styles, nil
}
decoder := xml.NewDecoder(bytes.NewReader(data))
decoder := newDocumentDecoder(data)
var id string
var current wordStyle
for {
Expand All @@ -118,7 +118,7 @@ func wordStyles(data []byte) (map[string]wordStyle, error) {
return styles, nil
}
if err != nil {
return nil, fail(Corrupt, DOCX, fmt.Errorf("styles.xml: %w", err))
return nil, xmlFailure(DOCX, fmt.Errorf("styles.xml: %w", err))
}
switch element := token.(type) {
case xml.StartElement:
Expand Down Expand Up @@ -154,7 +154,7 @@ func wordBullets(data []byte) (map[string]map[int]bool, error) {
if data == nil {
return out, nil
}
decoder := xml.NewDecoder(bytes.NewReader(data))
decoder := newDocumentDecoder(data)
abstract := map[string]map[int]bool{}
lists := map[string]string{}
var abstractID, numID string
Expand All @@ -165,7 +165,7 @@ func wordBullets(data []byte) (map[string]map[int]bool, error) {
break
}
if err != nil {
return nil, fail(Corrupt, DOCX, fmt.Errorf("numbering.xml: %w", err))
return nil, xmlFailure(DOCX, fmt.Errorf("numbering.xml: %w", err))
}
element, ok := token.(xml.StartElement)
if !ok {
Expand Down Expand Up @@ -224,7 +224,7 @@ type wordReader struct {
}

func (w *wordReader) read(ctx context.Context, body []byte) error {
decoder := xml.NewDecoder(bytes.NewReader(body))
decoder := newDocumentDecoder(body)
// skip is how deep the reader is in something that is not text a reader sees: a
// deletion kept for review, a field's code, a footnote's number.
skip := 0
Expand Down
22 changes: 19 additions & 3 deletions acceleration/internal/knowledge/extract/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,32 @@ func ReasonOf(err error) (Reason, bool) {
return "", false
}

// PageLimit is the error of a file with more pages than are allowed, among the TooLarge ones.
type PageLimit struct{ error }

func (p PageLimit) Unwrap() error { return p.error }

func fail(reason Reason, format Format, err error) error {
return stack.Wrap(&Error{Reason: reason, Format: format, Err: err})
}

// unreadable is err from reading a file's content: the deadline when reading was stopped
// by it, and otherwise a file that is corrupt.
// unreadable turns an error from reading a file's content into an extract error: the deadline
// when reading was stopped by it, TooLarge when the file went past a limit such as nesting,
// and Corrupt otherwise.
func unreadable(ctx context.Context, format Format, err error) error {
if ctx.Err() != nil {
return stack.Wrap(fmt.Errorf("extract: read the %s: %w", format, ctx.Err()))
}
return xmlFailure(format, err)
}

// xmlFailure turns an error from reading the XML of a file into an extract error: TooLarge when
// the XML is nested too deep, Corrupt otherwise.
func xmlFailure(format Format, err error) error {
var over overLimit
if errors.As(err, &over) {
Comment thread
kanat marked this conversation as resolved.
Resolved
return fail(TooLarge, format, err)
}
return fail(Corrupt, format, err)
}

Expand Down Expand Up @@ -301,7 +317,7 @@ func (e *Extractor) Extract(ctx context.Context, name string, data []byte) (Docu
return Document{}, err
}
if len(document.Pages) > e.options.MaxPages {
return Document{}, fail(TooLarge, format, fmt.Errorf("%s has %d pages, more than the %d allowed", name, len(document.Pages), e.options.MaxPages))
return Document{}, fail(TooLarge, format, PageLimit{fmt.Errorf("%s has %d pages, more than the %d allowed", name, len(document.Pages), e.options.MaxPages)})
}
document.Format = format
return document, nil
Expand Down
131 changes: 130 additions & 1 deletion acceleration/internal/knowledge/extract/extract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1568,14 +1568,143 @@ func (s *ExtractSuite) TestAPartNestedPastTheLimitIsRefusedBeforeItIsDecoded() {
runtime.ReadMemStats(&after)

s.requireReason(err, TooLarge)
s.Contains(err.Error(), "nested", name)
s.Contains(err.Error(), "deeper than a spreadsheet program writes them", name)
// The refused read allocates for the levels it reads up to the limit, a few KiB, and
// reading every level allocates more than a hundred bytes for each. The length of the part
// is far between the two.
s.Less(after.TotalAlloc-before.TotalAlloc, uint64(len(part.xml)), name)
}
}

const (
wordNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"`
odfNS = `xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"`
)

// wordPart is a Word document with a part of it replaced.
func (s *ExtractSuite) wordPart(name, xml string) []byte {
return s.rezip(s.fixture("handbook.docx"), map[string][]byte{name: []byte(xml)})
}

// openDocumentPart is an OpenDocument text with a part of it replaced.
func (s *ExtractSuite) openDocumentPart(name, xml string) []byte {
return s.rezip(s.fixture("handbook.odt"), map[string][]byte{name: []byte(xml)})
}

// An element nested far deeper than the limit makes a small Word or OpenDocument file, and
// encoding/xml keeps every level that is still open as it reads it. Each part the reader decodes is
// refused when it is too deep, whichever of them holds the elements.
func (s *ExtractSuite) TestAWordOrOpenDocumentPartNestedPastTheLimitIsRefusedBeforeItIsDecoded() {
nested := s.deep(1 << 18)
for name, test := range map[string]struct {
file string
data []byte
}{
"the Word body": {"a.docx", s.wordPart("word/document.xml", `<w:document `+wordNS+`><w:body>`+nested+`</w:body></w:document>`)},
"the Word styles": {"a.docx", s.wordPart("word/styles.xml", `<w:styles `+wordNS+`>`+nested+`</w:styles>`)},
"the Word numbering": {"a.docx", s.wordPart("word/numbering.xml", `<w:numbering `+wordNS+`>`+nested+`</w:numbering>`)},
"the Word relationships": {"a.docx", s.wordPart("word/_rels/document.xml.rels", `<Relationships>`+nested+`</Relationships>`)},
"the OpenDocument body": {"a.odt", s.openDocumentPart("content.xml", `<office:document-content `+odfNS+`><office:body><office:text>`+nested+`</office:text></office:body></office:document-content>`)},
"the OpenDocument styles": {"a.odt", s.openDocumentPart("styles.xml", `<office:document-styles `+odfNS+`>`+nested+`</office:document-styles>`)},
} {
s.Less(len(test.data), 128<<10, "%s: the file is small", name)

var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
_, err := s.extractor.Extract(context.Background(), test.file, test.data)
runtime.ReadMemStats(&after)

s.requireReason(err, TooLarge)
s.Contains(err.Error(), "deeper than a word processor writes them", name)
// Reading the part out of the archive and the rest of the file allocates two to three times the
// part's length. Reading every level of it allocates more than a hundred bytes for each, which
// is over fourteen times it.
s.Less(after.TotalAlloc-before.TotalAlloc, uint64(6*len(nested)), name)
}
}

// The body of an OpenDocument text is counted by its own reader, whatever the list styles read
// of it before. A reader that went on without its cap would hold every level that is open.
func (s *ExtractSuite) TestTheOpenDocumentBodyReaderRefusesABodyNestedPastTheLimit() {
body := `<office:document-content ` + odfNS + `><office:body><office:text>` + s.deep(1<<18) + `</office:text></office:body></office:document-content>`

err := (&odtReader{}).read(context.Background(), []byte(body))

var over overLimit
s.Require().ErrorAs(err, &over)
s.Contains(err.Error(), "nested")
}

// A reader that went on after the limit was passed would read the rest of the part as if the
// elements that follow were within it.
func (s *ExtractSuite) TestAPartStaysRefusedOnceItIsNestedPastTheLimit() {
tokens := &depthTokens{raw: xml.NewDecoder(strings.NewReader(strings.Repeat("<x>", maxXMLDepth+1) + "</x>")), nesting: nesting{what: "document", writer: "a word processor"}}
var first error
for first == nil {
_, first = tokens.Token()
}

for range 3 {
_, err := tokens.Token()

s.Equal(first, err)
}
}

// A part that is broken, and not nested too deep, is a corrupt file: only nesting is too large.
func (s *ExtractSuite) TestABrokenWordOrOpenDocumentPartIsRefusedAsCorrupt() {
for name, test := range map[string]struct {
file string
data []byte
}{
"a Word body closed by the wrong tag": {"a.docx", s.wordPart("word/document.xml", `<w:document `+wordNS+`><w:body><w:p></w:body></w:document>`)},
"a Word body that ends open": {"a.docx", s.wordPart("word/document.xml", `<w:document `+wordNS+`><w:body><w:p>`)},
"Word styles": {"a.docx", s.wordPart("word/styles.xml", `<w:styles `+wordNS+`><w:style></w:styles>`)},
"Word numbering": {"a.docx", s.wordPart("word/numbering.xml", `<w:numbering `+wordNS+`><w:abstractNum>`)},
"Word relationships": {"a.docx", s.wordPart("word/_rels/document.xml.rels", `<Relationships><Relationship></Relationships>`)},
"an OpenDocument body": {"a.odt", s.openDocumentPart("content.xml", `<office:document-content `+odfNS+`><office:body><office:text><text:p></office:text></office:body></office:document-content>`)},
"OpenDocument styles": {"a.odt", s.openDocumentPart("styles.xml", `<office:document-styles `+odfNS+`><office:styles>`)},
} {
_, err := s.extractor.Extract(context.Background(), test.file, test.data)

s.requireReason(err, Corrupt)
s.NotContains(err.Error(), "nested", name)
}
}

// An element of a Word or OpenDocument part may be nested as deep as the limit, counted from the
// part's root, and no deeper.
func (s *ExtractSuite) TestAWordOrOpenDocumentElementMayBeNestedAsDeepAsTheLimit() {
// Elements that follow one another are not nested, however many there are.
siblings := strings.Repeat("<x></x>", 2*maxXMLDepth)
for _, test := range []struct {
file string
data func(levels int) []byte
// root is how many elements enclose the nested ones, and inner how many hold the text.
root, inner int
}{
{"a.docx", func(levels int) []byte {
return s.wordPart("word/document.xml", `<w:document `+wordNS+`><w:body>`+strings.Repeat("<x>", levels)+`<w:p><w:r><w:t>Deep text</w:t></w:r></w:p>`+strings.Repeat("</x>", levels)+siblings+`</w:body></w:document>`)
}, 2, 3},
{"a.odt", func(levels int) []byte {
return s.openDocumentPart("content.xml", `<office:document-content `+odfNS+`><office:body><office:text>`+strings.Repeat("<x>", levels)+`<text:p>Deep text</text:p>`+strings.Repeat("</x>", levels)+siblings+`</office:text></office:body></office:document-content>`)
}, 3, 1},
} {
for _, past := range []bool{false, true} {
levels := maxXMLDepth - test.root - test.inner + btoi(past)
read, err := s.extractor.Extract(context.Background(), test.file, test.data(levels))

if past {
s.requireReason(err, TooLarge)
continue
}
s.Require().NoError(err, test.file)
s.Contains(read.Pages[0].Text, "Deep text", test.file)
}
}
}

// An element may be nested as deep as the limit, counted from the part's root, and no deeper.
func (s *ExtractSuite) TestAnElementMayBeNestedAsDeepAsTheLimit() {
for _, test := range []struct {
Expand Down
6 changes: 3 additions & 3 deletions acceleration/internal/knowledge/extract/odt.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,15 @@ func odtListStyles(data []byte, bullets map[string]map[int]bool) error {
if data == nil {
return nil
}
decoder := xml.NewDecoder(bytes.NewReader(data))
decoder := newDocumentDecoder(data)
style := ""
for {
token, err := decoder.Token()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return fail(Corrupt, ODT, err)
return xmlFailure(ODT, err)
}
element, ok := token.(xml.StartElement)
if !ok {
Expand Down Expand Up @@ -111,7 +111,7 @@ type odtReader struct {
}

func (o *odtReader) read(ctx context.Context, content []byte) error {
decoder := xml.NewDecoder(bytes.NewReader(content))
decoder := newDocumentDecoder(content)
Comment thread
kanat marked this conversation as resolved.
Resolved
body := false
// skip is how deep the reader is in something that is not text a reader sees: a
// footnote, a comment, a change kept for review.
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/knowledge/extract/pdf.go
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ func (e *Extractor) readPDF(ctx context.Context, data []byte) (Document, error)
return Document{}, fail(Corrupt, PDF, fmt.Errorf("the pages cannot be counted: %w", err))
}
if count.PageCount > e.options.MaxPages {
return Document{}, fail(TooLarge, PDF, fmt.Errorf("the PDF has %d pages, more than the %d allowed", count.PageCount, e.options.MaxPages))
return Document{}, fail(TooLarge, PDF, PageLimit{fmt.Errorf("the PDF has %d pages, more than the %d allowed", count.PageCount, e.options.MaxPages)})
}

pages := make([]pdfPage, 0, count.PageCount)
Expand Down
Loading
Loading