Archive

Archive for the ‘upb’ Category

pbstream’s name

May 3rd, 2009 Josh 9 comments

I hate naming things. I’m starting to realize that pbstream is outgrowing its name. That’s the one thing I always thought was brilliant about the iPod’s name. When the iPod started playing video it was no problem — it’s a pod! Why shouldn’t a pod play video? There’s no way to outgrow the name “iPod.” Brilliant.

I had no such luck with pbstream. The tagline is currently:

pbstream - a stream-oriented implementation of protocol buffers.

It’s true that offering streaming semantics is one distinguishing feature of my implementation, but the way it’s growing it’s no longer really “stream-oriented.” It will offer both stream-oriented and structure-oriented semantics. Both will be equally supported/encouraged — it will be a matter of what best suits your needs.

If anything, the number one distinguishing feature of my implementation is that it is minimal. It gives you a set of tools to use whatever paradigm is the right trade-off for you. It gives you building blocks to assemble as you see fit. There are never “riders” — things like memory management that you have to take along with the parts you really want.

So what’s in a name? Desired characteristics:

  • Unique, reasonably Googleable.
  • Communicates that it is a protobuf implementation, and if possible communicates the philosophy described above.
  • The name (or a reasonable abbreviation thereof) makes for a nice prefix that can be appended to all my identifiers. Right now it’s pbstream_this and pbstream_that.

Originally I just called it “pb” but that was a tad bit too generic. I slightly like “pblab” (communicates that it gives you building blocks for forging your own strategies), but I dislike the connotation that it is unfinished, unpolished, not production quality.

Perhaps I could give it a name, but keep using “pb_” in my identifiers. It could also help me organize the names of the different parts. I could use names like:

  • pb_stream_parser_* for the stream parser.
  • pb_struct_* for the code that defines an in-memory structure.

I kind of like that. But I still need a name for the package itself that is better than “pb”. Ideas?

Categories: upb Tags:

“Hey! It’s been months! What happened?”

May 3rd, 2009 Josh No comments

…reads the latest comment on my last entry. It’s true, I’ve gone silent for a few months. Work on pbstream has languished. The answer to “what happened?” is a combination of a personal life that got crazy and a brick wall I hit in the design of pbstream. But I think I have resolved the latter of those at least and work is progressing again.

So what is the brick wall I hit with pbstream? I had conflicting goals that I couldn’t figure out how to reconcile. One goal was to include as little policy related to memory management as humanly possible. In other words, if you’re using pbstream to store fully-parsed protobufs in memory — I’ll use the SAX vs. DOM analogy again, where this is the DOM case — then I want pbstream to not define any semantics for how the memory for that tree is managed. Is it reference-counted, garbage-collected, or is it just allocated/deallocated in one big chunk? Every runtime already has its own answer to this question. I don’t want to include a memory management strategy, which adds to the code size and complexity, just to have it be an annoying thing that you have to integrate into whatever runtime you’re already using.

Or, as I said in a previous entry: Oh fantastic! Because definitely the one thing that my application doesn’t already have is a memory manager.

On the other hand, I realized that I really do want the ability to pass an in-memory protobuf representation between language implementations. For example, if there’s a C library that conjures up some complex protobuf, I want to be able to pass that parsed in-memory protobuf to Python without serializing/deserializing. I want different runtimes to be able to look at this memory and make sense of it.

So far so good. This alone doesn’t require memory management. But I also wanted two things that do pose a memory-management problem:

  • I wanted to pass protobufs between language implementations without copying.
  • I wanted one language implementation to be able to modify the protobuf that had been created by a different language implementation.

The first is a problem because if you take a protobuf you created in C and pass it to Python, once that Python returns C has no idea whether Python has taken references to any of the protobuf’s data. If C frees the protobuf, Python could try to later read from the freed memory. If C doesn’t free the protobuf, the memory will leak. The fundamental problem is that C and Python have no way of cooperating to be sure the memory is freed only when the last reference that either of them holds is dropped.

The second is a problem for a similar reason. Suppose you take a protobuf you created in C and pass it to Python, and Python wants to mutate that protobuf. Suppose the protobuf has a submessage, which is implemented as a reference to that other message. If in python you say:

message.submessage = other_submessage

…Python now has to decide what to do with the submessage that message already had. Should it free it or not? If you free it and C had a reference to it, C references freed memory. If you don’t free it and C doesn’t have a reference to it, it leaks.

I fretted over the question of what to do about this for weeks. I didn’t want to give up the ability to pass protobufs between languages without serializing/deserializing. But I was loath to include the slightest amount of memory management code because of the implied complexity, run-time overhead, and code size effects. So everything ground to a halt while I tried to reconcile these conflicting desires in my head.

At one point I convinced myself that the only way out was reference-counting. The in-memory protobufs themselves would contain one extra integer for the reference count, and the code would contain just these little extra reference count increments/decrements and checks. Then C and Python would both maintain reference counts to these shared data structures. For Python it would be a sort of two-stage reference counting, since the individual Python objects would be reference-counted, and when their reference count dropped to zero they would decrement the reference count of the shared protobuf structure one.

Eww, Eww, EWW!! Now maybe you can understand a bit better why I haven’t gotten anything done for a while. There’s no way I could be very happy implementing this scheme.

So quite recently I found a way to relax the sharing requirements just enough that I can get away with not implementing any memory management. My new strategy is:

  • language A can reference language B’s protobufs, but only for as long as B guarantees that all the references will continue to be valid. In most cases this just means that when B calls A and passes a protobuf, A can only reference B’s protobufs before it returns control back to B.
  • In general, languages cannot mutate each other’s protobufs unless they have some special arrangement with regards to memory management. I thought I really needed this capability in Gazelle, but I’m no longer convinced I do.

So with that resolved, work is resuming, and I hope to have some results soon. I always hate making promises though, because I’m unwilling to press on when I don’t have a satisfactory answer to a question (as the last month demonstrates), and this can delay my progress long beyond my original intentions.

Categories: upb Tags:

C Compilers

March 3rd, 2009 Josh 3 comments

So the more I work on pbstream (and I’m working on it quite a lot) the more obsessed I get with making it perfect. I’m no longer just out to just write some good software, my new goal is to utterly demolish this problem space with blindingly utter perfection. It’s going to be one of the best things I’ve ever done.

So my latest OCD goal this quest is to make it truly 100% C99 compliant: compilable on the weirdest and most nontraditional target, and free of any undefined behavior. I like most people have spent several years lulled into the x86/GCC monoculture. It’s time for me to transcend that narrow-minded view.

So I’ve set out to obtain every C compiler and lint tool I can possibly find, hoping that each one can show me even the smallest spot of imperfection that I can proceed to purge from my crystalline statements and declarations. I was ashamed to realize that I couldn’t even think of a time I had used a non-GCC/MSVC compiler in almost five years, and I didn’t know which ones were available to me. I am happy to say that I have eradicated some of that ignorance, and already have found some bugs that GCC didn’t show me!

So what C compilers are out there? Here are some of the ones I came across:

  • Sun Studio, Sun’s C and C++ compiler. To my surprise, it is available for free. Includes a lint tool.
  • Intel C++ Compiler. You can obtain a non-commercial version for free if you absolutely, totally, cross-your-heart promise that you are not compensated in any way for your work. I have a vision of the Intel guys following around open-source developers at conferences and revoking them their non-commercial licenses at the first sign of any swag.
  • Digital Mars C and C++ compiler, which is freely available for Windows and DOS.
  • Visual C++ Express is a free download from Microsoft. Apparently has very poor C99 support though.
  • The Portland Group has a C and C++ compiler, but there doesn’t seem to be any way to use it without paying several hundred dollars.
  • Comeau has a C and C++ compiler that takes great pride in its standards-compliance. You just have to get over the curiously awful web page, which actually says “Bursting With So Much Language Support It Hurts!” No free use (though at $50, it’s not a big hurdle — I paid more for a parking ticket today. If only I hadn’t had six such parking tickets to pay. For parking on my own street. But that’s a story for another day). There is a web form (!) where you can paste your code and see error/warning messages though, which could be all you need to test standards-compliance.
  • SDCC, the Small Device C Compiler is a GPL’d C compiler that targets tiny embedded processors. I was looking quite forward to this one as a target that is wildly different from other C compilers. Unfortunately, though it has partial C99 support, it does not support 64-bit integer types, and I’m not quite willing tilt at that particular windmill of making pbstream portable to compilers without 64-bit integer support.
  • TCC, the Tiny C Compiler. Fabrice Bellard is an absolute bad-ass, but unfortunately TCC doesn’t seem to support much of C99 (it choked on a for loop that defined a variable).
  • Clang, the LLVM compiler. My version of Ubuntu doesn’t seem to have this available, and I always find LLVM a bit of a pain to compile and install from source, but I would like to try this when I get the chance.

So this should be enough variety that I can feel confident making smug assertions about pbstream’s portability. Now the only question is whether I’ll shell out $50 for the Comeau compiler just for that added potential for portability smugness.

Categories: upb Tags:

The art of hashing

March 1st, 2009 Josh 9 comments

It might sound strange for me to call hashing an art. After all, it’s about the most fundamental data structure we’ve got, after arrays, linked lists, and binary trees. It’s been studied extensively for fifty years. What amount of “art” could possibly be left in such a topic?

I’ve learned to anticipate that there are dark and unstudied corners in even the most fundamental computer science topics. And hashing appears to be no exception. I’m investigating hashing at the moment because I need hash tables in a few places for my rapidly-developing Protocol Buffers implementation pbstream. So I wanted to take a quick survey of the state-of-the-art in hash tables, and implement a minimal hash table that suits my needs.

What are my needs? If someone defines a protobuf like so:

message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}

…I need to build two hash tables for looking up fields: one keyed by number (1, 2, 3) and one keyed by name (name, id, email).

You might say “why not just use an array for looking up fields by number?” Indeed that’s what I’ll do in most cases, but field numbers can be as large as 2**27 and needn’t be allocated densely. So gracefully degrading to a hash table is important (one practical reason why the field numbers might not be dense is if the client is using extensions). To get the best of both worlds I’ll follow Lua’s lead and have the field number table be a hybrid array/hashtable, where the size of the array part is such that it’s at least half full.

My usage pattern for these hashtables is that I’ll build them once (when I parse a .proto file), then do lookups in the critical path of parsing. So insert time is practically irrelevant, but lookup time is extremely important, because it’s in my critical path. I’ll gladly trade some memory for fast lookups.

So I figured I’d take a few hours to discover the state-of-the-art in hashtables, implement that, and be on my merry way. Unfortunately there doesn’t seem to be much agreement about what the state of the art even is!

Let’s start with even the simple and most basic question: how big should a hashtable be? The literature differs here: some of it claiming that hashtables should have sizes that are prime numbers and some saying they should be powers of two.

But once you’ve decided that, you’ve only just entered the jungle of collision-resolution strategies. There are a lot of them, and it’s not at all clear to me that the trade-offs are well understood. A list of ones I’ve come across, and my current understanding of what they mean:

  • linear probing: if your hash function is h(k), then a collision in T[h(k)] means you should also try T[h(k)+i] for i=1 to some limit.
  • quadratic probing: like linear probing, but also throw in a T[h(k) + i + j^2], to spread it out a little.
  • double hashing: like linear probing, but you scale the jumps by another hash function: T[h(k) + g(k)*i].
  • chaining: all entries that collide are in a linked list, so for lookups you search this list. chaining can be either internal (table entries have both values and links, links point to other locations in the table) or external (table is just pointers to the head of linked lists, inserts always allocate a new node).
  • cuckoo hashing: Wikipedia makes this sound like hashing’s best-kept-secret. You use two hash functions: if you do an insertion and the spot you want is taken, you kick whatever was already there out and put it in its alternate spot.
  • two-way chaining: use two hash functions (like cuckoo and double hashing), but you use the two hash values to find the two possible chains the value could be in.

Few papers seem to offer a comprehensive account of the trade-offs between these. Some authors claim that linear probing is best on modern CPUs because of excellent locality (cache-friendly), but this paper [PDF] takes exception to that claim, saying that the better overall performance of double-hashing negates the cache effects. And indeed, none of the real-world implementations I found use linear probing.

A quick survey of mainstream hashing implementations shows that they can’t agree on what’s best either.

  • Lua uses internal chaining with powers-of-two table sizes and “Brent’s variation” (so-named because of a 1973 paper called Reducing the retrieval time of scatter storage techniques — so much for caching-conscious schemes).
  • Ruby uses internal chaining with prime table sizes.
  • Python uses a custom probing scheme. You have to read the comments in the source file itself — they do more to make hashing sound like black magic than I possible could.
  • Perl appears to use external chaining, but its code is a bit hard to follow.

Even if you decide on a collision strategy, you still have to decide on a hash function, and there are surprises lurking for you there as well. Conventional wisdom about hashing is that you want a hash function that randomly distributes the inputs to the outputs. But Python and Lua both hash integers to themselves (so h(5) = 5)!

There are just a dizzying number of variations on hashing. Given my relatively simple use case (one-time construction, lookup speed trumps all) you’d think there would be a clear and obvious answer. But I don’t see one.

Given my deep respect for Lua’s implementation, I’m tempted to just start with that and worry about trying to optimize it later. I’m slightly disconcerted with its focus on getting good performance even when the table is quite full, because as I mentioned for my use case I’ll gladly trade modest amounts of RAM for faster lookup. At least it’s someplace to start.

But seriously, who knew that hash tables had so many variations, with no clear winner?

Categories: upb Tags: