Longest balanced bracket stretch

Write longest_valid(text) that returns the length of the longest stretch of text, made only of ( and ), that is a correctly balanced bracket string.

longest_valid("(()")      ->  2
longest_valid(")()())")   ->  4
longest_valid("")         ->  0

A stack of indices with a sentinel: push on (, pop on ), and the length of the current valid stretch is the distance from the current index to the top of the stack.

def longest_valid(text):
    ...