Repository navigation
Add optional concurrent filing downloads - #1986
Conversation
dgunning
left a comment
There was a problem hiding this comment.
Thanks for this. It works, and I'd like to merge it after two small additions.
I ran it against SEC on 12 PEP 8-Ks that weren't in the HTTP cache. Four workers got 17.8 MB/s, against 8.0 MB/s for one worker on a similar set. Every stored file was a complete submission under the right accession number. All requests still go through the shared client and rate limiter, so a higher max_workers can't push past SEC's limit. When I made the first of 40 downloads fail, the error reached the caller after 9 requests, so the pool cancels the rest of the batch rather than finishing it in the background. Grouping duplicates by accession number is the right way to keep two threads off the same .part file.
Before merging:
- All the tests fake the HTTP layer. Could you add one network test with a cassette that downloads two or three known accessions with
max_workers=2and checks the stored files? AGENTS.md asks for at least one assertion on a real filing. - Please add
max_workersto the download parameters indocs/api/filings.md, with a note that it only applies tosource='submission'with given filings. (sourceis missing from that list too, which isn't your doing, but it would be good to add both.)
Smaller things, take or leave:
- In
_download_single_submission, the localpartial(the.nc.partpath) hides thefunctools.partialthe module now imports. Something likepart_filewould read better. pool.mapyields results in submission order, so one slow early filing holds the progress bar even when later ones have finished.as_completedwould keep it moving.- Each worker holds a whole submission in memory before writing it, so a high
max_workerson large filings multiplies peak memory. A sentence in the docstring would cover it. - The "groups duplicate filings together" comment could say why: two workers writing the same
.partfile would collide. - The barrier test only passes because the number of distinct accessions is even. With an odd number it hangs for 5 seconds and fails on a barrier timeout. A comment there would save someone a confusing failure later.
|
Thanks for testing this against real filings. I added a cassette-backed test that downloads two PepsiCo 8-Ks with max_workers=2 and verifies the accession number and primary document in each saved submission. I also documented source and max_workers, including that multiple workers apply to selected filings downloaded with source="submission". All seven focused tests passed locally, including the replay test with new recording disabled. The changes are in a3912e0. |
dgunning
left a comment
There was a problem hiding this comment.
Thanks for adding the PepsiCo test and the docs. The approach looks right to me, and keeping max_workers=1 as the default means nobody's existing downloads change. There's one thing I'd like fixed before merging, plus a few smaller ones.
Errors and Ctrl-C don't stop the concurrent path. pool.map submits every group up front, and when an exception comes out of the loop, leaving the with ThreadPoolExecutor block calls shutdown(wait=True) without cancelling anything. So if filing #3 of 5,000 gets a 500, the remaining downloads all still run (around nine minutes at the SEC rate limit) before the user sees the error, and Ctrl-C looks like a hang for the same reason. With max_workers=1 both stop immediately, and I'd like the concurrent path to behave the same way. Cancelling pending futures on the way out (shutdown(cancel_futures=True) in a try/finally), or submitting in bounded batches, would do it. Could you add a test for this too? A fake fetch that returns a 404 for one accession and raises for another, with max_workers=2, would cover the not-found accounting and the early stop together.
A few smaller things:
pool.mapyields in submission order, so one slow or retrying download holds the progress bar at zero while the others finish behind it. Iterating withas_completedgives live progress.- All workers share the same rate limiter, so anything above about 10 workers adds no throughput, and the time spent waiting on the limiter counts against each request's timeout and retry budget. I'd cap
max_workersor warn above the limit. - The sequential and concurrent paths order duplicate filings differently. I think a single executor path would be simpler, since
ThreadPoolExecutor(max_workers=1)covers the sequential case, anddefaultdict(list)can replace the manual grouping. - The
isinstance(max_workers, int)check rejectsnumpy.int64, which is easy to end up with when the value comes from a DataFrame.operator.index(max_workers)accepts it. - In
_download_single_submission, the local variablepartialnow shadows thefunctools.partialthis PR imports. Renaming it topart_pathavoids a confusing error later. - The network test creates an HTTP manager with
get_http_mgr(cache_enabled=False)and never closes its client. Closing it in a fixture finalizer would stop the connection leak.
|
Thanks for catching the shutdown behavior. I replaced pool.map() with batches of up to max_workers accession groups and update progress as each group finishes. If a download raises or the user presses Ctrl-C, pending work is canceled, active requests can finish, and later batches are never submitted. The default single-worker path still processes filings in input order. I added tests for a 404 followed by a download error and for Ctrl-C on the calling thread. Both check that later filings are never requested. All nine targeted tests passed locally, including the replay for the two PepsiCo filings. |
dgunning
left a comment
There was a problem hiding this comment.
Thanks, this covers everything from my last review. Errors and Ctrl-C now stop the download, and I checked that both new tests fail on the previous pool.map version, so they really pin the behaviour.
One more change before I merge. Submitting in batches means every batch waits for its slowest download, so a single 10-K holds three idle workers. In a simulation with 120 filings and 4 workers, mostly small filings with some 10-K-sized ones, this version took 4.99 s against 2.11 s for the previous one. Could you switch to a sliding window? Keep up to max_workers groups in flight, and each time wait(..., return_when=FIRST_COMPLETED) returns, submit the next group. It still stops early, because nothing new is submitted after an error and the finally still cancels.
The error test will then need a small change. With a sliding window, filing #3 can start as soon as #1's 404 frees a slot, so I'd assert that filings 4–6 are never requested and that nothing is stored, rather than that exactly #1 and #2 were requested.
|
Thanks for benchmarking this. I switched the downloader to a sliding window that keeps up to max_workers groups in flight and refills freed slots after checking the completed results. If a download raises or the user presses Ctrl-C, it stops submitting work and runs the existing cancellation cleanup. The updated test checks that filing #3 starts while #2 is still running and that filings #4–6 are never requested after the error. All nine targeted tests passed, including the PepsiCo cassette replay. In a local simulation with 120 filings and four workers, median runtime went from 0.403 s to 0.170 s across five runs per version. |
|
I pushed b5b4d38 to make each SEC accession one download job per call. We originally grouped duplicate entries to keep two workers from writing the same temporary file while preserving the sequential loop’s behavior. That meant [A, A] could fetch the same submission twice with overwrite_existing=True, even though the first fetch had already refreshed the local file. I think the clearer rule is to treat repeated accessions as one request to store the same filing. overwrite_existing=True still refreshes a file that was already on disk. A duplicate entry also no longer triggers a second attempt after a 404. This applies to both the single-worker and concurrent paths. That lets us remove the duplicate-group loop and its stop flag. The sliding window still limits work in flight and stops submitting jobs on an error or Ctrl-C. All 10 targeted tests passed, including the PepsiCo cassette replay with a repeated accession. |
dgunning
left a comment
There was a problem hiding this comment.
Thanks for working through all of this. The sliding window does what I asked: it keeps max_workers downloads in flight, stops submitting after an error or Ctrl-C, and the finally cancels whatever is still queued. Treating a repeated accession as one request is a clearer rule than the duplicate groups, and it removed a fair amount of code.
I merged current main into the branch locally and ran it. The six threaded tests passed on six consecutive runs, and the 252 fast tests under tests/storage and every other test that calls download_filings or .download() pass. I also ran the PepsiCo test with outbound sockets blocked: it passes from the cassette and fails once the cassette is removed, so it really replays.
One small change to the changelog fragment before I merge: it needs a measured value. The throughput from my first review would do, something like "four workers downloaded 12 PepsiCo 8-Ks at 17.8 MB/s, against 8.0 MB/s for one". If you push that, I'll merge it for 6.5.
|
Thanks for verifying the downloads and cassette replay. I added your benchmark to the changelog: four workers downloaded 12 uncached PepsiCo 8-Ks at 17.8 MB/s, compared with 8.0 MB/s for one worker on a similar set. The changelog check passed. |
What this changes
Selected SEC filing submissions previously downloaded one at a time. Callers can now set
max_workersto download multiple submissions concurrently. The default is still one worker.Fixes #1985
Verification
ValidationErrorwith an explanatory message.The six focused tests passed. They verify that two downloads can overlap, the configured worker limit is respected, and a duplicate filing is fetched once when overwriting is disabled. The tests use mocked HTTP responses. Live SEC verification and the broader fast suite are pending.
AI assistance