Saturday, July 5, 2008

Watch out for the "Texas School for the Blind" van

The title may at first appear to be a joke. But as we were leaving a July 4th fireworks show last night, a white van cut us off in the maylay of traffic that clearly everyone was having to deal with while leaving the park.Sure, people cut you off. It happens. No need to get angry.

Then -- I saw it. The van had a giant Texas School for the Blind placard on the side.First some minor chuckles. Then a real 'lol' moment. The irony of being cut off by *this* specific van was too much. And yes, hah hah -- I get that a blind person was not driving. It's still funny. Boo-hiss on you.

Then the real question settled in -- not to be insensitive, but what were they doing at a fireworks display anyway... listening to them go off?

Genius Bar: a.k.a. Mac'tard Central

I succumbed to the infamous burnt power supply issue with my MacBook Pro. After two years of solid use and abuse, it finally gave up the ghost.


I'm still covered under AppleCare pro support, and as this is a known issue -- I figure getting a new adaptor is a no-brainer. A quick call to the AppleCare support line, and the nice gentleman on the other end agrees. We make an appointment for the next day at the local apple store. In the mean time, I head to Fry's to pick up a new supply, as this is my work machine. My battery is also crappy and lasts less than an hour, and I've got plenty more work to do than that.

The next day, I head to my "Genius Bar" appointment around lunch time. Right on time, my name is called. This is the last thing the genius does well.

First, he has no idea why I'm there. Second, he has no idea I'm currently under AppleCare pro coverage. The phone support representative said both of things would be "in the system" and I'd be taken care of right away. There are three possibilities here. Either the genius didn't check the system to see why I was there, or the phone support person did not put the info in the system, OR... there is no system at all.

Second, I have to convince the mac'tard -- oops, genius -- that I'm really covered by apple care. I brought my laptop just in case, but I also had my original apple care coverage certificate. The mac'tard says "duhhh, errrr... I'm not sure it has the info I need to look up your information. Can I just get the serial number from your computer?" Look, mac'tard -- right THERE (I show him) -- that IS the serial number. "duhhh, errrrr --- let me enter it in and see if it works." Needless to say, it was the correct serial number. The astonished "genius" then declares me valid and legal.

Now, as if I was not having enough fun already...

I finally get the requisite "so, what seems to be the problem." Eyes, rolling, I said "'scuse me, while I whip this out" (boy, I wish I really did say that). I show him my obviously charred power adaptor. The genius is perplexed. He turns it over, and around, and flexes the cable, smells it, etc. I'm surprised he didn't stick his tongue on the burnt part to taste it.

After several minutes of deep contemplation, the answer comes: "I believe your adaptor shorted out." WOW. I bow and kneel in the awesome presence of the obviously superior mac-intellect of the certified Genius standing before me. Clearly, I am not worthy and should run from the store screaming giddy joy like a little school girl.

Due to my obviously lesser mac-intellect, I now get the obligatory/deragotory solution that these geniuses must be trained to dole out. "Sir, we will replace your adaptor THIS time... but let me show you how to wrap your cord so it doesn't happen again. See, you need to loop the thin cord before wrapping it around the posts..." I stop him mid-sentence (and yes, this part is true). I pull out my brand-new adaptor (purchased the night before) from my laptop bag. It has the very stress-reducing loop of which he was so graciously attempting to inform me. I actually say "I'm not retarded. I've done it this way for TWO YEARS." [blank stare -- both directions] "uhhhh, ok. let me get that part for you."

Finally convinced of his mac'tardedness, the genius fetches a new power brick from the back. Sign here, date that. And, I'm done.

So, I get that the genius bar probably spends 99% of the time dealing with regular idiots. I mean, we are talking about the apple store here. But I'm quite certain, when I show you a burnt, charred power adaptor -- you should just fetch me a new one.

At the end of the day, I now have two power supplies -- which actually makes life a tad easier for this nomadic worker. My primary work-spot at home now has a permanent adaptor. Setting up and leaving that spot is slightly less of a burden.

Apple support sent me a follow-up email, asking me to rank the "experience." I'm definitely going to reply with the appropriate negative feedback, but boy am I tempted to just link to this post...

Wednesday, June 18, 2008

Hibernate: Cache Queries the Natural Id Way

I work on the MySQL Enterprise Tools team, formerly of MySQL and now with Sun Microsystems. The 2.0 version of the Enterprise Monitor is well under way. As part of this, the Java server backend has been refactored to utilize Spring and Hibernate. Honestly, I didn't know either one of those technologies before starting this project. Oh, what a fun road it has been...

A big draw for using an off-the-shelf ORM was so that we didn't have to write our own (kind of bad and slightly wrong -- those darn transactions) caching implementations for the custom one-off ORM that existed previously. A lot of our internal meta-model is very static, so clearly caching would be a HUGE win for performance, right?

Not so fast, turbo. Let me continue...

The headline feature for the 2.0 Monitor is "Query Analysis." Coupled with the MySQL Proxy, the Monitor receives captured query data to/from a MySQL server. Once at the monitor, the data can be aggregated, analyzed, and reported upon. What better test for this feature than to use it on ourselves, to tune ourselves!

And this brings me back to hibernate caching. In the course of monitoring ourselves, I noticed that a certain query was happening WAY more than it should be, just based on my gut feeling. The query in question loaded an object that was generally static -- save for one value that represents the frequency of how often some data should be collected. Its the only mutable value, and once in place, it rarely changes.

Hrm... how to debug. First, we checked the cache settings. Whoops -- WAY too low for both the cache expiry timeout and the max cache elements. Fix that. Still sucks. Some cursory hibernate source and log perusal showed that the cache for these objects was being invalidated at a rapid rate. Yes, the entire cache. Even though the objects are essentially static, the query cache takes the safe route and says any change to a related table invalidates any and all queries that reference that table. This makes sense, from a generic cache standpoint. But I thought to myself -- surely there has to be a way. *I* am smarter than hibernate in this case, and *I* can more rightly determine when the query results should be invalidated. Lucky for me, hibernate allows you to extend the StandardQueryCache "up to date" policy checks. w00t. I implemented one, overrode the timeout policy for the object(s) in question, and re-ran tests. FAILURE. Turns out I am not smarter than hibernate.

However, in the process of implementing the custom query cache policy, I had debugged through some more hibernate code and noticed that "natural id" queries are treated special. Some more google-fu, and quickly I come across Queries by Natural Identifier in the hibernate docs.

Now, the docs just aren't real clear on what optimizations can be made internally by utilizing the Criteria with a natural id restriction. But, as I was just in that section of code, I could correlate it. Here's the meaty bit -- if you make a natural id / key lookup, and hibernate recognizes it as such, it can bypass the table timestamp invalidation and go directly to second-level cache to fetch the object. Hibernate knows, with an immutable and unique natural key, that a table modification will not effect the composition of the object in question (of course, an object modification would, and it would have been evicted from L2 cache).

I cannot overemphasize the utility of this discovery. You see, we were making frequent inserts into the table. But existing objects (rows) where changed almost never. But without the natural key lookup, the inserts invalidated all results in the query cache. There you have why I was seeing way more selects for the same objects than I had anticipated.

Some quick assurances that we mapped the natural id correctly, some quick refactoring of the HQL into Criteria queries with natural id restrictions, and whammo, we're good. Lets run the tests and query analysis again... ruh roh. OH COME ON! (not my exact reaction, but I think you can guess what it was really like).

Confident that the natural id cache lookup optimization was what I really really really wanted, there had to be something else going on. More debuggage ensued. I set a breakpoint near the same area in StandardQueryCache where I first noticed the query cache optimization in the first place. Lo and behold, the hibernate metadata for saying "i am a natural key lookup" was returning false.

I am not amused. I am confident my hibernate mapping is correct, because the unique index was present in the schema. Think. Think. Think. Well, I had recently been on an effort to move from the hbm xml mappings to hibernate annotations mappings. @NaturalId support was, in fact, the very reason I had recently upgraded the annotations jar. On a hunch, I reverted the persistence mapping back to the xml form. Debug, the metadata returns the correct value... test, and YES, finally -- the queries issued are in line with my expectations and the rows present in the database. I. Have. Won.

Being the good open-source citizen, I made a hibernate forum post that detailed my findings, including simplified sample code demonstrating the problem. The good folks on the hibernate forum (after questioning the sillyness of my contrived example) were quick to recognize the problem, and I got a hibernate jira issue opened.

The workaround, obviously, is leave the xml mapping in place until the fix makes it into a hibernate release. Not too bad of a deal, I guess, considering the overall win I now have in my cache hit ratio.

In conclusion -- if it makes sense for your data model, the natural id query cache optimization can be a huge performance win for your app. If you have immutable, or rarely changed objects with a constant natural key lookup -- look into the Criteria natural id restriction. And, use the xml mapping until the bug is fixed.

ps -- there is one other performance note to consider, actually. If using the natural id query, and it returns no rows, this NULL result will not be cached. So, if you have more of these than 'object/row found' results, you will still get tons of these queries that you don't expect. Either stop using the natural key optimization (if 'not found' is more common), or extend your object/schema to include a 'not supported' field. In our case, the lack of a row meant "not supported" and we had a flag "not supported" in case it was supported, but then went away. In those cases where something was frequently "not supported" I simply went ahead and created the object/row and just set the flag to false -- thus ensuring the natural key optimization was not subverted.


Free Light Show

A few weeks ago some really bad storms came through central Texas. Since I watch TV via DVR, I had no idea there was a storm coming, much less the severity of them. I didn't find out until I came back to my computer, and several friends had IMd me "it's headed right for you!" and "are you in your basement" (to which, in Texas -- no one has basements).

I flipped on the news, and the weatherman was speaking of some obvious rotation "two miles north/northeast of pflugerville." Yeah, uhh... that's right about where I live. In fact, the weatherman's map showed it probably went about a mile north of my house.

But, strangely enough -- no damage. The rest of Austin had plenty, but we survived without a scratch. Perhaps, because we have no trees at all in our neighborhood...

I captured some lo-res video of the lightning. Give it a bit at the beginning, it's not easy to capture lightning video, you know.


Tuesday, June 17, 2008

Dueling Shared Libraries

I'm famous! Well, in my own mind. I've made it onto Jan Kneschke's blog, as we tackled an ugly problem on Mac OS X when trying to use a self-built MySQL Monitor Agent.

I won't plagerize, so go read it yourself.

JUnit Eats Your Memory

Once again, we started getting OutOfMemoryError's in our JUnit test suite. Some necessary refactoring re-introduced me to an old foe that I had battled once before. I figured, what the hell -- an excellent opportunity for my first blog post.

There's an important FAQ in JUnit that should be bold, blinking, italics, and highlighted. The gist is -- if you assign an instance member in a JUnit TestCase (declaration, setUp(), or otherwise), you damn well better assign it to null in tearDown().

You see, JUnit creates an instance of the TestCase class for EVERY test method. It would have you believe, the way it is architected, that the TestCase class in question is instantiated once, every test method is called with setUp() and tearDown() pre- and post-, and all is glorious. But that is not the case. Every test method gets its own test case instance. Oh -- and the important detail -- ALL the classes have references held on them until the END of the test suite run.

So, if you do any sort of non-trivial testing with even moderately large (but transient) objects, be sure to set the refs in your testcase to null in tearDown() so they can be garbage collected.

Better yet -- lets find a newer tool than JUnit. Just because it is ubiquitous doesn't mean it is the best tool.