We have a bug in our application that does not occur every time and therefore we don't know its "logic". I don't even get it reproduced in 100 times today.

Disclaimer: This bug exists and I've seen it. It's not a pebkac or something similar.

What are common hints to reproduce this kind of bug?

+23  A: 

Add some sort of logging or tracing. For example log the last X actions the user committed before causing the bug (only if you can set a condition to match bug).

Bryan Denny
+2  A: 

Try to add code in your app to trace the bug automatically once it happens (or even alert you via mail / SMS)

log whatever you can so when it happens you can catch the right system state.

Another thing- try applying automated testing that can cover more territory than human based testing in a formed manner.. it's a long shot, but a good practice in general.

+1  A: 

Read the stack trace carefully and try to guess what could be happened; then try to trace\log every line of code that potentially can cause trouble.

Keep your focus on disposing resources; many sneaky sporadical bugs i found were related to close\dispose things :).

+3  A: 

What development environment? For C++, your best bet may be VMWare Workstation record/replay, see:

Other suggestions include inspecting the stack trace, and careful code overview... there is really no silver bullet :)

+1  A: 

"Heisenbugs" require great skills to diagnose, and if you want help from people here you have to describe this in much more detail, and patiently listen to various tests and checks, report result here, and iterate this till you solve it (or decide it is too expensive in terms of resources).

You will probably have to tell us your actual situation, language, DB, operative system, workload estimate, time of the day it happened in the past, and a myriad of other things, list tests you did already, how they went, and be ready to do more and share the results.

And this will not guarantee that we collectively can find it, either...

+3  A: 

Add verbose logging. It will take multiple -- sometimes dozen(s) -- iterations to add enough logging to understand the scenario. Now the problem is that if the problem is a race condition, which is likely if it doesn't reproduce reliably, so logging can change timing and the problem will stop happening. In this case do not log to a file, but keep a rotating buffer of the log in memory and only dump it on disk when you detect that the problem has occurred.

Edit: a little more thoughts: if this is a gui application run tests with a qa automation tool which allows you to replay macros. If this is a service-type app, try to come up with at least a guess as to what is happening and then programmatically create 'freak' usage patterns which would exercise the code that you suspect. Create higher than usual loads etc.

Mmm, I like that idea of a rotating log buffer. Not necessarily trivial to implement in all cases, but a good idea nonetheless
+2  A: 

all the above, plus throw some brute force soft-robot at it that is semi random, and scater a lot of assert/verify (c/c++, probably similar in other langs) through the code

+1  A: 

I'd suggest to write down all things that user has been doing. If you have lets say 10 such bug reports You can try to find something that connects them.

Tomek Tarczynski
+17  A: 

Analyze the problem in a pair and pair-read the code. Make notes of the problems you KNOW to be true and try to assert which logical preconditions must hold true for this happen. Follow the evidence like a CSI.

Most people instinctively say "add more logging", and this may be a solution. But for a lot of problems this just makes things worse, since logging can change timing-dependencies sufficiently to make the problem more or less frequent. Changing the frequency from 1 in 1000 to 1 in 1,000,000 will not bring you closer to the true source of the problem.

So if your logical reasoning does not solve the problem, it'll probably give you a few specifics you could investigate with logging or assertions in your code.

"Changing the frequency from 1 in 1000 to 1 in 1,000,000 will not bring you closer to the true source of the problem."But changing it to 1 in 1 will. If you can happen across a change that increases the bug frequency, you're that much closer to finding and fixing it.
Carl Manaster
I don't believe in stumbling upon solutions and experience has shown me that careful analysis and elimination is almost always a winner in these cases. I think some background variables like test coverage, programming language features and access to the running system can influence the measures you use to solve such problems. If the database is unavailable to you when you're to solve the problem, you pretty much have to rely on logs or other reports, right ?
+2  A: 

Tons of logging and careful code review are your only options.

These can be especially painful if the app is deployed and you can't adjust the logging. At that point, your only choice is going through the code with a fine-tooth comb and trying to reason about how the program could enter into the bad state (scientific method to the rescue!)

+2  A: 

Often these kind of bugs are related to corrupted memory and for that reason they might not appear very often. You should try to run your software with some kind of memory profiler e.g., valgrind, to see if something goes wrong.

Tuomas Pelkonen
+2  A: 

Along with a lot of patience, a quiet prayer & cursing you would need:

  • a good mechanism for logging the user actions
  • a good mechanism for gathering the data state when the user performs some actions (state in application, database etc.)
  • Check the server environment (e.g. an anti-virus software running at a particular time etc.) & record the times of the error & see if you can find any trends
  • some more prayers & cursing...


+2  A: 

Let’s say I’m starting with a production application.

  1. I typically add debug logging around the areas where I think the bug is occurring. I setup the logging statements to give me insight into the state of the application. Then I have the debug log level turned on and ask the user/operator(s) notify me of the time of the next bug occurrence. I then analyze the log to see what hints it gives about the state of the application and if that leads to a better understanding of what could be going wrong.

  2. I repeat step 1 until I have a good idea of where I can start debugging the code in the debugger

  3. Sometimes the number of iterations of the code running is key but other times it maybe the interaction of a component with an outside system (database, specific user machine, operating system, etc.). Take some time to setup a debug environment that matches the production environment as closely as possible. VM technology is a good tool for solving this problem.

  4. Next I proceed via the debugger. This could include creating a test harness of some sort that puts the code/components in the state I’ve observed from the logs. Knowing how to setup conditional break points can save a lot of time, so get familiar with that and other features within your debugger.

  5. Debug, debug , debug. If you’re going nowhere after a few hours, take a break and work on something unrelated for awhile. Come back with a fresh mind and perspective.

  6. If you have gotten nowhere by now, go back to step 1 and make another iteration.

  7. For really difficult problems you may have to resort to installing a debugger on the system where the bug is occurring. That combined with your test harness from step 4 can usually crack the really baffling issues.

+7  A: 

It's quite common for programmers not to be able to reiterate a user-experienced crash simply because you have developed a certain workflow and habits in using the application that obviously goes around the bug.

At this frequency of 1/100, I'd say that the first thing to do is to handle exceptions and log anything anywhere or you could be spending another week hunting this bug. Also make a priority list of potentially sensitive articulations and features in your project. For example : 1 - Multithreading 2 - Wild pointers/ loose arrays 3 - Reliance on input devices etc. This will help you segment areas that you can brute-force-until-break-again as suggested by other posters.

Jelly Amma
+1  A: 

For .NET projects You can use Elmah (Error Logging Modules and Handlers) to monitor you application for un-caught exceptions, it's very simple to install and provides a very nice interface to browse unknown errors

This saved me just today in catching a very random error that was occuring during a registration process

Other than that I can only recommend trying to get as much information from your users as possible and having a thorough understanding of the project workflow

They mostly come out at night.... mostly

Nick Allen - Tungle139
+5  A: 

There's a good chance your application is MTWIDNTBMT (Multi Threaded When It Doesn't Need To Be Multi Threaded), or maybe just multi-threaded (to be polite). A good way to reproduce sporadic errors in multi-threaded applications is to sprinkle code like this around (C#):

Random rnd = new Random();

and/or this:

for (int i = 0; i < 4000000000; i++)
    // tight loop

to simulate threads completing their tasks at different times than usual or tying up the processor for long stretches.

I've inherited many buggy, multi-threaded apps over the years, and code like the above examples usually makes the sporadic errors occur much more frequently.

+16  A: 

There is no general good answer to the question, but here is what I have found:

  1. It takes a talent for this kind of thing. Not all developers are best suited for it, even if they are superstars in other areas. So know your team, who has a talent for it, and hope you can give them enough candy to get them excited about helping you out, even if it isn't their area.

  2. Work backwards, and treat it like a scientific investigation. Start with the bug, what you see is wrong. Develop hypotheses about what could cause it (this is the creative/imaginative part, the art that not everyone has the talent for) - and it helps a lot to know how the code works. For each of those hypotheses (preferably sorted by what you think is most likely - again pure gut feel here), develop a test that tries to eliminate it as the cause, and test the hypothesis. Any given failure to meet a prediction doesn't mean the hypothesis is wrong. Test the hypothesis until it is confirmed to be wrong (although as it gets less likely you may want to move on to another hypothesis first, just don't discount this one until you have a definitive failure).

  3. Gather as much data as you can during this process. Extensive logging and whatever else is applicable. Do not discount a hypothesis because you lack the data, rather remedy the lack of data. Quite often the inspiration for the right hypothesis comes from examining the data. Noticing something off in a stack trace, weird issue in a log, something missing that should be there in a database, etc.

  4. Double check every assumption. So many times I have seen an issue not get fixed quickly because some general method call was not further investigated, so the problem was just assumed to be not applicable. "Oh that, that should be simple." (See point 1).

If you run out of hypotheses, that is generally caused by insufficient knowledge of the system (this is true even if you wrote every line of code yourself), and you need to run through and review code and gain additional insight into the system to come up with a new idea.

Of course, none of the above guarantees anything, but that is the approach that I have found gets results consistently.

#2 is actually amazingly good advice... if you remember it. Just stopping to *actually think* for a good few minutes can save much grief, but at the time there's always too much pressure to just clack away at a keyboard.
+6  A: 

Since this is language-agnostic, I'll mention a few axioms of debugging.

Nothing a computer ever does is random. A 'random occurrence' indicates a as-yet-undiscovered pattern. Debugging begins with isolating the pattern. Vary individual elements and assess what makes a change in the behaviour of the bug.

Different user, same computer? Same user, different computer? Is the occurrence strongly periodic? Does rebooting change the periodicity?

FYI- I once saw a bug that was experienced by a single person. I literally mean person, not a user account. User A would never see the problem on their system, User B would sit down at that workstation, signed on as User A and could immediately reproduce the bug. There should be no conceivable way for the app to know the difference between the physical body in the chair. However-

The users used the app in different ways. User A habitually used a hotkey to to invoke a action and User B used an on-screen control. The difference in the user behaviour would cascade into a visible error a few actions later.

ANY difference that effects the behaviour of the bug should be investigated, even if it makes no sense.

I've seen similar issues - an impatient user who didn't just click, but (if memory serves) triple-clicked on buttons. And the system at the time was caching the clicks, so if the subsequent screen had a button in the same location... You get the idea. That one I only solved by actually sitting with the user and watching her use the app.
Carl Manaster
+2  A: 

Unit Tests. Testing a bug in the app is often horrendous because there is so much noise, so many variable factors. In general the bigger the (hay)stack, the harder it is to pinpoint the issue. Creatively extending your unit test framework to embrace edge cases can save hours or even days of sifting

Having said that there is no silver bullet. I feel your pain.

+2  A: 

Add pre and post condition check in methods related to this bug.

You may have a look at Design by contract

Pierre-Jean Coudert
Yes, I have had success using assert() in this way in C++. Check *everything*!
Zan Lynx
+1  A: 

The team that I work with has enlisted the users in recording their time they spend in our app with CamStudio when we've got a pesky bug to track down. It's easy to install and for them to use, and makes reproducing those nagging bugs much easier, since you can watch what the users are doing. It also has no relationship to the language you're working in, since it's just recording the windows desktop.

However, this route seems to be viable only if you're developing corporate apps and have good relationships with your users.

Kevin Brill
+1  A: 
+2  A: 

Assuming you're on Windows, and your "bug" is a crash or some sort of corruption in unmanaged code (C/C++), then take a look at Application Verifier from Microsoft. The tool has a number of stops that can be enabled to verify things during runtime. If you have an idea of the scenario where your bug occurs, then try to run through the scenario (or a stress version of the scenario) with AppVerifer running. Make sure to either turn on pageheap in AppVerifier, or consider compiling your code with the /RTCcsu switch (see for more information).

+1  A: 

@p.marino - not enough rep to comment =/

tl;dr - build failures due to time of day

You mentioned time of day and that caught my eye. Had a bug once were someone stayed later at work on night, tried to build and commit before they left and kept getting a failure. They eventually gave up and went home. When they caught in the next morning it built fine, they committed (probably should have been more suspiscious =] ) and the build worked for everyone. A week or two later someone stayed late and had an unexpected build failure. Turns out there was a bug in the code that made any build after 7PM break >.>

We also found a bug in one seldom used corner of the project this january that caused problems marshalling between different schemas because we were not accounting for the different calendars being 0 AND 1 month based. So if no one had messed with that part of the project we wouldn't have possibly found the bug until jan. 2011

These were easier to fix than threading issues, but still interesting I think.

:) Actually what I was hinting at was bugs linked to timezones, system time being set different from "real" time, daylight saving hours etc. - but yes, sometimes it's something completely unthinkable...

hire some testers!

+1  A: 

This has worked for really weird heisenbugs. (I'd also recommend getting a copy of "Debugging" by Dave Argans, these ideas are partly derived form using his ideas!)

(0) Check the ram of the system using something like Memtest86!

The whole system exhibits the problem, so make a test jig that exercises the whole thing. Say it's a server side thing with a GUI, you run the whole thing with a GUI test framework doing the necessary input to provoke the problem.

It doesn't fail 100% of the time, so you have to make it fail more often.

Start by cutting the system in half ( binary chop) worse case, you have to remove sub-systems one at a time. stub them out if they can't be commented out.

See if it still fails. Does it fail more often ?

Keep proper test records, and only change one variable at a time!

Worst case you use the jig and you test for weeks to get meaningful statistics. This is HARD; but remember, the jig is doing the work.

I've got No threads and only one process, and I don't talk to hardware

If the system has no threads, no communicating processes and contacts no hardware; it's tricky; heisenbugs are generally synchronization, but in the no-thread no processes case it's more likely to be uninitialized data, or data used after being released, either on the heap or the stack. Try to use a checker like valgrind.

For threaded/multi-process problems:

Try running it on a different number of CPU's. If it's running on 1, try on 4! Try forcing a 4-computer system onto 1. It'll mostly ensure things happen one at a time.

If there are threads or communicating processes this can shake out bugs.

If this is not helping but you suspect it's synchronization or threading, try changing the OS time-slice size. Make it as fine as your OS vendor allows! Sometimes this has made race conditions happen almost every time!

Obversely, try going slower on the timeslices.

Then you set the test jig running with debugger(s) attached all over the place and wait for the test jig to stop on a fault.

If all else fails, put the hardware in the freezer and run it there. The timing of everything will be shifted.

Tim Williscroft

Use an enhanced crash reporter. In the Delphi environment, we have EurekaLog and MadExcept. Other tools exist in other environments. Or you can diagnose the core dump. You're looking for the stack trace, which will show you where it's blowing up, how it got there, what's in memory, etc.. It's also useful to have a screenshot of the app, if it's a user-interaction thing. And info about the machine that it crashed on (OS version and patch, what else is running at the time, etc..) Both of the tools that I mentioned can do this.

If it's something that happens with a few users but you can't reproduce it, and they can, go sit with them and watch. If it's not apparent, switch seats - you "drive", and they tell you what to do. You'll uncover the subtle usability issues that way. double-clicks on a single-click button, for example, initiating re-entrancy in the OnClick event. That sort of thing. If the users are remote, use WebEx, Wink, etc., to record them crashing it, so you can analyze the playback.

Chris Thornton