Keep a ZIP import within its CometAPI budget by limiting archive members and measured decompressed bytes, validating the complete import before any model call, and giving every resulting attempt one shared job allowance. Include chunk summaries, a final combined summary, retries, and fallbacks in that allowance. A compressed upload-size limit cannot establish how much text or how many paid requests the job will create.

This guide is for engineers building a server-side feature that summarizes uploaded text collections through CometAPI. The example accepts a flat ZIP of UTF-8 text files. PDFs, office documents, recursive archives, and automatic tool execution require separate processing policies.

Last reviewed: November 19, 2026 (Asia/Shanghai and UTC).

Decide what one ZIP is allowed to create

Start with the product task: one authorized user imports one collection and receives one result. Keep that parent job identity through upload inspection, text staging, chunk planning, and model dispatch. Giving each extracted file an independent default budget lets the archive’s member count determine the total exposure.

The Python ZIP reference warns that decompression bombs can exhaust disk space. It also distinguishes ZipInfo.compress_size from ZipInfo.file_size, the compressed and uncompressed member sizes. Neither the upload’s byte count nor its file count alone covers the whole expansion.

OWASP’s File Upload Cheat Sheet recommends limits after decompression and says ZIP uploads are generally discouraged because they can contain many file types. Offer individual text uploads if the product does not need archives. When ZIP import is necessary, define a narrow accepted format and reject the rest before inference.

For this workflow, accept ordinary text-file entries with approved names, supported compression, and strict UTF-8 decoding. Reject directories, duplicate normalized names, encrypted members, special-file entries, and nested archives. Do not recursively open a member because its contents resemble another archive. An extension or client-provided content type alone does not validate the content.

Keep inspection in a worker with bounded memory, CPU time, elapsed time, and temporary storage. That worker does not need a CometAPI credential or permission to dispatch inference. Apply those resource limits before opening the ZIP: parsing the central directory itself consumes resources before an application can count its entries.

Put a limit at each expansion boundary

Use independent controls for upload transfer, decompression, text processing, and model work. The following values are illustrative application policy, not CometAPI limits or a recommended setting for every product:

BoundaryExample allowanceEnforcement point
Uploaded archive5 MiBCount received bytes while accepting the upload
Archive entries100, including entries later rejectedInspect metadata before reading member content
One decompressed member512 KiBCheck metadata, then count bytes returned while reading
Whole decompressed archive8 MiBShare one actual-byte counter across all members
Archive nestingNoneReject archive members; never recurse
Model dispatches for the parent job52 total attemptsClaim allowance before each outbound handoff

Here, one MiB is 1,048,576 bytes and one KiB is 1,024 bytes. Count the received upload rather than trusting only a declared content length. Store it under an application-generated identifier outside the webroot, following the OWASP guidance.

Use advertised uncompressed sizes to reject obviously oversized archives early. Then enforce the limits on actual bytes returned by the decompressor. A compression-ratio check can flag unusual input, but it cannot replace absolute limits: many individually modest members can still exceed the aggregate allowance.

Avoid an unrestricted extractall() followed by a directory-size check. That sequence discovers the problem after expansion. For text summarization, read members through the archive interface into bounded staging; there is no need to recreate their supplied filesystem paths. Validate filenames anyway so duplicate handling and result attribution remain unambiguous.

Count decompressed bytes before publishing staged text

Python documents ZipFile.infolist() for inspecting entries and ZipFile.open() for reading a member as a binary file-like object. Pass the inspected ZipInfo object to open(); the reference specifically notes that this is useful when archives contain duplicate names. This workflow rejects duplicates during metadata validation.

The helper below demonstrates the byte-counting stage. Its input is a seekable upload already bounded to the transfer limit. Run the format, name, encryption, and special-file checks described above before calling it, and keep the process resource limits active. It deliberately has no model client or dispatch callback.

from zipfile import ZipFile


class ImportRejected(ValueError):
    pass


def stage_members(upload, *, max_entries=100,
                  per_member=512 * 1024, total_limit=8 * 1024 * 1024):
    staged = []
    expanded = 0
    with ZipFile(upload) as archive:
        entries = archive.infolist()
        if not entries or len(entries) > max_entries:
            raise ImportRejected("entry count")

        for entry in entries:
            if entry.is_dir():
                raise ImportRejected("flat files only")
            if entry.file_size > per_member:
                raise ImportRejected("member size")
            if entry.file_size > total_limit - expanded:
                raise ImportRejected("archive size")

            allowance = min(per_member, total_limit - expanded)
            data = bytearray()
            with archive.open(entry) as member:
                while True:
                    # Read at most one byte beyond the remaining allowance.
                    size = min(64 * 1024, allowance - len(data) + 1)
                    part = member.read(size)
                    if not part:
                        break
                    data.extend(part)
                    if len(data) > allowance:
                        raise ImportRejected("expanded-byte limit")

            expanded += len(data)
            staged.append(bytes(data))
    return staged

The one-byte probe distinguishes exact-limit EOF from content exceeding the allowance. The aggregate count survives the move to the next member. Header sizes provide an early rejection; the bounded reads protect the staging path while content is consumed.

The function returns only after every member has been read. If a later member is corrupt, unsupported, or oversized, discard the staged collection and reject the import. Catch ZIP, decompression, decoding, and policy failures at the job boundary; do not convert an exception into permission to process the earlier files. Do not run testzip() as an unbounded preliminary check: Python documents that it reads all files to check headers and CRCs.

After staging succeeds, decode each member strictly and validate the accepted text format. Retain text only in the protected job store. This helper bounds returned bytes; it is not a complete file-security validator or a CPU-time limiter. A blocked decompression call needs the external worker deadline to terminate it.

Seal the chunk plan before admitting CometAPI spend

Build the complete chunk manifest from the validated collection before dispatching its first request. Pin the parser and chunker revisions, model route, prompt revision, and output policy. Store opaque member references and chunk ordinals so the job can resume without rediscovering a different set of work.

Count the complete request for each chunk, including instructions and any overlap. Use the site’s CometAPI token-counting workflow for the model-specific estimate and its limitations. Decompressed bytes are an admission measure; they are not a universal token conversion.

For example, suppose the sealed manifest contains 24 members, each producing two approved chunks. That is 48 chunk-summary requests. Add one combined-summary request and reserve three additional attempts for recovery: the parent allowance is 52 attempts. These are synthetic planning numbers. The upload count remains one throughout.

Budget the combined summary explicitly. Joining all chunk summaries can exceed its input ceiling even when every chunk request fits. Plan a bounded reduction tree if necessary, counting every intermediate request, or reject the plan. Do not let a summarizer invent additional reduction levels after approval.

For a token-priced text route with no extra billed operations, an illustrative conservative calculation is:

job_token_charge_allowance = Q * (I * input_rate + O * output_rate) / 1,000,000

Q covers all permitted attempts; I and O bound the full input and generated tokens of every attempt. Rates are approved amounts per million tokens for the same route and currency. Use rates that cover the applicable billing categories. If attempts have different bounds or rates, sum their separate allowances instead.

With 52 attempts, a 4,000-token input ceiling and a 400-token generation ceiling would allow at most 208,000 input tokens and 20,800 generated tokens within that assumed scope. These figures become useful financial bounds only when counting, request limits, pricing, and dispatch coverage are verified. They do not cap parsing costs, taxes, unrelated requests, or unbudgeted tools.

CometAPI’s chat-completion reference documents model, messages, max_completion_tokens, and response usage. Its generation ceiling includes reasoning and visible output. Keep the approved model and compatible output parameter under server control, use one completion choice, and disable unplanned tools and fallback routes. A browser-supplied options object must not expand the sealed plan.

Keep every worker inside the same parent allowance

Before each outbound attempt, claim one attempt slot and reserve its covered cost against the parent job. Make competing claims atomic across workers; copying the remaining balance into each child does not share it. The atomic reservation guide covers that mechanism separately.

Give retries their own attempt identities and debit the same parent allowance. A timeout after dispatch leaves its cost unresolved; it does not restore a slot or prove that the provider performed no work. Hold uncertain reservations for reconciliation. Reopening a failed worker must not issue a fresh 52-attempt allowance for the same import.

Once an attempt completes, retain reported prompt_tokens, completion_tokens, and relevant breakdowns with the request and pricing references. CometAPI states that its usage counts support billing and that completion usage includes reasoning tokens. Reconcile calculated cost against available billing evidence; missing usage stays unresolved.

Keep filenames, extracted text, prompts, completions, archive contents, and credentials out of ordinary cost events. Record parent ID, policy revision, entry count, actual expanded bytes, planned chunks, admitted attempts, denial reason, settled cost, and outstanding reservations. Parsing and temporary-storage expenses belong in their own cost lines.

Verify rejection before testing a paid route

Exercise the import with synthetic ZIPs and a counted fake dispatcher first. Local checks for this article covered exact byte boundaries, member and aggregate overflow, entry overflow, and a corrupt later member. They made no model requests. The production workflow still needs the integration checks below:

Fixture or eventRequired observation
Valid collection exactly at an approved byte boundaryStaging succeeds without silently truncating content
One member or the aggregate exceeds its allowanceImport is rejected; no model attempt is dispatched
Too many entries, including many empty membersEntry-count rejection occurs before member processing
Nested archive, duplicate name, encrypted member, or invalid UTF-8Format rejection occurs before inference
A corrupt member follows several valid membersEarlier staged text produces zero model calls
Planned reduction adds more calls than approvedPlan is rejected before the first dispatch
Two workers compete for the final attempt slotOne claim wins; the other defers without dispatch
Worker loses a response or restartsExisting parent state and unresolved cost remain in force

Keep test archives small; a scaled fixture can prove a threshold without creating a real decompression bomb. Check worker termination and temporary-data cleanup separately. Lowering a threshold for a test does not prove the deployed production value, so read back the active policy revision too.

Choose one import feature, write its accepted archive format, and implement the late-member rejection case first. Then seal its chunk manifest and verify the shared attempt allowance. For a subsequent, separately budgeted route check, Start with CometAPI and reconcile one approved text request before enabling the full import.

Sources checked

Three primary public references returned HTTP 200 during live research on November 19, 2026 UTC. These maintained technical references support an evergreen import-control task; no new product release or universal model price is assumed. Match the ZIP runtime and model route to the versions actually deployed.

  • Python: zipfile — Work with ZIP archives — member inspection and reads, duplicate-name handling, compressed and uncompressed size fields, CRC testing, and decompression resource pitfalls. The served documentation identifies Python 3.15.2 and a November 19 update; the helper uses established interfaces also available in the local Python runtime.
  • OWASP: File Upload Cheat Sheet — narrow file acceptance, distrust of supplied content type, storage outside the webroot, ZIP risks, and limits after decompression. Used as current upload-design guidance, not as a guarantee that these checks establish file safety.
  • CometAPI: Create a chat completion — request fields, generation ceilings including reasoning, and usage accounting. Used as the current endpoint reference. The archive policies, numerical allowances, manifest workflow, and acceptance criteria are application recommendations derived from the documented interfaces.