At every death time the patients still at risk form a 2×2 table: group by died or survived. If the two groups had the same hazard, the deaths would fall on the groups like a random draw without replacement from those at risk, so the number in group 1 is hypergeometric, with a known mean and variance. The log-rank test adds up observed minus expected over all death times and divides by the square root of the summed variances. Step through the death times to watch the sum build up, and compare the result with a permutation test that shuffles the group labels.
Group 1 is the first group listed. At a death time with r at risk (r1 in group 1) and q deaths, the expected number of group-1 deaths is q r1/r (11.5) and its variance q(r1/r)(1 − r1/r)(r − q)/(r − 1) (11.6). The statistic is W = Σ(q1 − E)/√ΣVar (11.8), approximately standard normal; R's survdiff reports W². The envelope is ±1.96 times the square root of the variance summed so far.
code/ch11_lab.py (logrank_test) and code/ch11_lab.R (survdiff).