New York kdb Training 2017
Spaces still available. Register now to learn Kdb+.

Debugging q code in kdb

Kdb+ provides limited tools for debugging, we have break points but navigating the call stack to find current variable values is difficult as you will see below:

'Breakpoints / :Return

From within functions kdb supports both standard returns and exceptions. At any time :1 could be used within a function to return value 1 immediately and prevent further statements being executed. e.g. {a:x+1; :x+2; a} 1 will return the value 3.

Similarly an exception can be signaled and execution halted by using single quote e.g. 'err. You may have seen this happen when you cause an error e.g. {x+1} `a Execution is stopped inside the function and the console shows q)). While inside this break mode, remote calls are halted, variables inside the function are visible and execution control will only be returned to the main loop when you enter a single slash \. Here are some examples:

During break mode

When a break occurs, execution is halted at the level of the call stack that the exception was thrown. During a break we can:

  1. Use :return or 'break to move further up the call stack.
  2. Use .z.s to see what function we are in. (this is not always clear)
  3. use show on complex variables like tables etc. to get standard output formats.

Other useful functions

  • 0N! - Shows a value in the console and pass it through an expression simultaneously
  • -3! - "returns the string representation of x."

Catching a break

Rather than break mode occurring, we can wrap a section of code using protected evaluation. Any exceptions that occur within protected evaluation can be handled without rising all the way up the stack and causing break mode. (similar to try/catch in other languages like java) e.g.:

Breaking on exceptional client calls

By default only functions entered at the console result in break mode being thrown, This can also be applied to client queries using system command \e 1 (0 turns off, 1 turns on) . This should only be used for testing for as mentioned, when in break mode remote queries are queued on a stack and not executed until the function returns.

Interrupt a frozen q process

At the q console Control-C can be used to interrupt a long running command in some cases. Control-C sends a SIGINT which if the running q command supports it, interrupts and returns early. It is also possible to send an interrupt from the linux terminal using the command kill -SIGINT processPIDHere. When interrupted successfully the console will show a 'stop exception and break at the current position in the stack: