Repository navigation
Make kastore_open() work with non-seekable files. - #88
Conversation
Codecov Report
@@ Coverage Diff @@
## master #88 +/- ##
==========================================
+ Coverage 99.66% 99.70% +0.03%
==========================================
Files 7 7
Lines 895 1004 +109
Branches 51 66 +15
==========================================
+ Hits 892 1001 +109
Misses 1 1
Partials 2 2
Continue to review full report at Codecov.
|
|
Upon further investigation, this looks like it will be an API change in order to signal EOF back to the user. I managed to get the following test code working. The python engine would need more effort. $ cat kas_stream.py
#!/usr/bin/env python3
import sys
import kastore
import time
if len(sys.argv) != 2 or sys.argv[1] not in ("read", "cread", "write", "cwrite"):
print(f"usage: {sys.argv[0]} [read | cread | write | cwrite]", file=sys.stderr)
exit(1)
engine = kastore.PY_ENGINE
if sys.argv[1] in ("cread", "cwrite"):
engine = kastore.C_ENGINE
sys.argv[1] = sys.argv[1][1:]
if sys.argv[1] == "read":
i = 0
while True:
i += 1
try:
data = kastore.load("/dev/stdin", read_all=True, engine=engine)
except EOFError:
break
print(f"data[{i}] = {data}", file=sys.stderr)
elif sys.argv[1] == "write":
data = { "t": [time.clock_gettime_ns(time.CLOCK_BOOTTIME)],
"foo": [0x66, 0x6f, 0x6f] }
kastore.dump(data, "/dev/stdout", engine=engine) |
|
Thanks for this @grahamgower, it's very helpful. I agree we should support reading tskit files from a stdin, so let's figure out how to make this work. One thing to bear in mind though, is that currently tskit keeps the kastore open for the lifetime of a table collection object, as it uses the memory from the kastore for columns. This is a relic of an attempt to make tree sequence loading copy-free by using mmap. However, it turns out that mmap is inherently unsafe (if someone truncates the file while it's mmap'd you get a bus error) and that actually memcopying a few gigs of data (at most) is pretty quick, so there's no point in worrying about it. So we want to move away from this in tskit, and we'll then be compatible with reading from stdin. Probably another change we'll want to make is to pass a file descriptor through to kastore so that we can read from arbitrary pipes rather than having some protocol for interpreting strings. I guess what we want is another How about we line up a quick call to chat through the details @grahamgower? cc @benjeffery --- this is relevant to stuff we were talking about on Friday. |
Yep, this was probably going to be my next move. There's some weirdness with the test code I posted if it's changed to Happy to have a chat this afternoon if you're free. This is just for some hobby code btw, so I might not follow up particularly strongly if it looks too involved. |
Sure, say 2pm BST? No pressure to take things any further - even if we just get this specced out in a some issues we've done good work here. |
|
2pm BST works for me. |
jeromekelleher
left a comment
There was a problem hiding this comment.
This is great, thanks @grahamgower. As we discussed, it might be simplest to refactor the Python API now to get rid of mmap (#58) so we can don't seek any more. We can add the stuff for supporting arbitrary files afterwards as a follow on.
|
I think that just leaves fixing certain tests to expect |
|
Needs a few more tests for the exception paths in |
jeromekelleher
left a comment
There was a problem hiding this comment.
Looks great, thanks @grahamgower! I'm not convinced the semantics of EOF'ing any time we get a truncated stream is what we want to do, but maybe I'm wrong.
|
Still needs more test coverage, but most of the changes are done. It turns out that supporting streaming without using |
|
Looks good, thanks @grahamgower. My queue has built up a bit over the weekend, so I'll need to loop back on this one and think it through properly. Should get to it in a couple of days. |
jeromekelleher
left a comment
There was a problem hiding this comment.
This is great, thanks @grahamgower! On reflection I think it's simpler if we do actually implement access to this in the C Engine in the Python API. Probably the simplest way to do this is to add another argument, fd to the kastore_dump() and kastore_load() functions in the low level API. This is mutually exclusive with filename. If fd is specified, we create a FILE* from it using fdopen.
Or, probably a simpler thing to do would be to create a new pair of functions, dumpf and loadf which just take an fd. This can then be linked up with the high-level API easily enough.
Or, maybe we could use the Python C API to take in a python file obj, and get an FILE* from it? I'm not sure what the best approach is. But, anyway, I think we do need to do it, or we'll never have full confidence in the C API working from pipes, etc.
I think the first of these suggestions is the path of least resistance. I'll have a think, play with some code, and get back to you. |
* Remove call to fseek when the KAS_READ_ALL flag is set. * Signal EOF, so the user can detect when a stream has been closed.
Changes are analogous to those made for the c engine, in particular: * Don't use tell(), and don't seek() with read_all=True. * Remove mmap (restructuring the Store class was necessary anyway).
|
Back around the merry-go round. :) The C tests are still missing. And |
I ended up doing something more like your third suggestion, but creating the FILE* using fdopen. Python 3 doesn't use FILE* internally (unlike python 2), which means the only option is to use the python object's fileno(). |
jeromekelleher
left a comment
There was a problem hiding this comment.
This is AWESOME @grahamgower, really excellent! I can have a go at tweaking the streaming tests if you like? I'd also like to write some low-level tests to make sure we're getting all the corner cases in the Python-C interface (stuff like passing a bad fd and making sure we clean up properly). But we're basically done, I think.
Yes, please do. I likely wont get back to this for a couple of weeks, so I'd be happy if you polished and/or whacked any bits you're not entirely convinced about. |
|
OK, great. I'll make a pass at this and get back to you for final approval before merging. |
93edab1 to
fc0b85c
Compare
|
Grrr. I still can't get a working test case for the socket case. Everything works fine (well almost, there's still some bugs in the Py engine) when I run this program: import socketserver
import socket
import sys
import kastore
import numpy as np
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
print("{} connected:".format(self.client_address[0]))
for data in self.server.data_list:
# encoded = kastore.dumps(data)
# print("Writing", len(encoded), "bytes")
# self.request.sendall(encoded)
kastore.dump(data, self.request.fileno(), engine=kastore.C_ENGINE)
if __name__ == "__main__":
HOST, PORT = "localhost", 9990
data_list = [{"a": np.arange(j * 1000, dtype=np.int8)} for j in range(200)]
if sys.argv[1] == "1":
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.data_list = data_list
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
else:
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
received_list = []
while True:
try:
d = kastore.load(sock.fileno(), engine=kastore.PY_ENGINE, read_all=True)
except EOFError:
break
received_list.append(d)
print("recieved", len(received_list))
for a, b in zip(received_list, data_list):
# print(a, b)
assert len(a) == len(b)
finally:
try:
sock.close()
except OSError as ose:
print("Error on sock close", ose)But when I try to run the Socket test cases (which basically to the same thing) it's deadlocking. It seems to be blocking on creating the server handler threads, but I've no idea why. It must be something to do with the fact we're using fds rather than actual sockets. This is a very good test though, so I'd really like to get it working. Any chance you could have a go @grahamgower? |
|
I really don't know what's going on here @jeromekelleher, but the use of |
|
Ah! It's more informative without unbuffered output enabled (no |
|
Ok, I'm an idiot. I overwrote the fileno() method but didn't return a value. :) |
|
Huh, playing around with this a bit more, looks like it's blocking on the FD at the client side. If we use plain recv's at the client it works (even if the server is writing to the fd)... |
|
Yep, I've just now discovered the same thing. Are you seeing the print() statements from the server thread? I'm not. I changed it to use a multiprocessing.Process instead of a thread, and now I see the server print()s. |
|
Spoke too soon, it deadlocks all right just later on when we move more stuff around. Probably there's some issue with threading, you're right. |
|
I reckon it's a buffering issue with the underlying |
I'm trying out a different architecture using a Process for the server. Let's see. |
|
Helps if we write to the request file descriptor. |
|
Nice, great stuff @grahamgower. I figured out a different way to make it work, but lets do both. I'll update here in a bit, and ask for a final review from you then. |
Ok, sounds good. I'll stop pushing to the branch. |
|
Your one is still deadlocking for me occasionally @grahamgower - mind if I rewind the branch back to where I was and force-push so you can see what I've done? |
|
Sure, go ahead. I ran my version in a loop for a while and couldn't provoke any problems. Maybe there's a version descrepancy? |
bb6c8df to
334f961
Compare
|
OK, done. Can you have a look through please @grahamgower? What do you think of the EchoServer stucture - seems pretty robust to me now as communication between the processes is kept to a minimum. I'm happy to bring in your version of the server in too, if you like - it's probably testing slightly different weird timing stuff, which does shake out bugs. I'm fairly sure it was deadlocking for me, but I can try it again if we want to put it in. Assuming we're happy with this now I think we can merge. If you're happy I/you can rebase and squash my commits into one. Ready to merge then I think. |
|
Looks good @jeromekelleher, I'm just slightly worried about the call to |
|
Sorry, I have to run off and do other things now @jeromekelleher. But it looks great, so please squish and merge! |
|
will do @grahamgower. Thanks for all this work, this is a huge power-up for tskit-dev!!! |
334f961 to
3d7c1d5
Compare
- Bump C API to 2.0
3d7c1d5 to
1115ec4
Compare
7e16cf7 to
15f2d15
Compare
I'd like to read tree sequences from a pipe (e.g. /dev/stdin or a FIFO). There doesn't seem to be any reason this shouldn't be possible. I wasn't sure of the best place to put the tests (C and Python tests wanted, I guess?), so figured I'd submit this as is.