#!/usr/bin/env Rscript
# Benchmarks for design section 16. Run from the package root, against the
# installed zuproto:
#
#   R CMD INSTALL . && tools/run-benchmarks [n]
#
# n messages (default 10^6) of a type with five scalar fields are decoded
# into a data frame, from a list of raw vectors and from a length-delimited
# stream, and singly with proto_decode() for comparison. RProtoBuf is timed
# too when it is installed. Record the results in .agents/design.md.

suppressPackageStartupMessages(library(zuproto))
args <- commandArgs(trailingOnly = TRUE)
n <- as.integer(if (length(args) > 0) as.numeric(args[[1]]) else 1e6)

pool <- proto_pool()
# The schema, written with descriptor.proto's own types so no protoc is
# needed: message bench.Row { int64 id = 1; double value = 2; int32 count = 3;
# bool flag = 4; string name = 5; }
field <- function(name, number, type) {
  list(name = name, number = number, label = "LABEL_OPTIONAL", type = type, json_name = name)
}
set <- proto_encode(
  list(file = list(list(
    name = "bench.proto", package = "bench", syntax = "proto3",
    message_type = list(list(name = "Row", field = list(
      field("id", 1L, "TYPE_INT64"), field("value", 2L, "TYPE_DOUBLE"),
      field("count", 3L, "TYPE_INT32"), field("flag", 4L, "TYPE_BOOL"),
      field("name", 5L, "TYPE_STRING")
    )))
  ))),
  "google.protobuf.FileDescriptorSet", pool
)
proto_pool_add(pool, set)

time <- function(label, expr) {
  gc()
  t <- system.time(force(expr))[["elapsed"]]
  cat(sprintf("%-46s %8.2f s\n", label, t))
  invisible(t)
}

# Pool loading first (design section 16: a 1 MB descriptor set in under
# 50 ms), before the large allocations below slow R's garbage collector: a
# synthetic set of one file with enough message types to reach 1 MB.
types <- lapply(seq_len(2600), function(i) {
  list(name = sprintf("M%04d", i), field = lapply(seq_len(12), function(j) {
    field(sprintf("field_%02d", j), j, if (j %% 2) "TYPE_INT64" else "TYPE_STRING")
  }))
})
big <- proto_encode(
  list(file = list(list(name = "big.proto", package = "big", syntax = "proto3", message_type = types))),
  "google.protobuf.FileDescriptorSet", pool
)
t_pool <- min(vapply(1:5, function(i) system.time(proto_pool(big))[["elapsed"]], numeric(1)))
cat(sprintf("%-46s %8.3f s  (%.2f MB)\n", "proto_pool(), a descriptor set of", t_pool, length(big) / 1e6))

# One small message of a large schema, decoded many times (#82): 2000 proto2
# types, each holding the next, each extended by one of them. The arena
# ceiling walks every reachable type once per pool, not once per call.
chained <- lapply(seq_len(2000) - 1L, function(i) {
  next_field <- if (i < 1999L) {
    list(c(field("next", 1L, "TYPE_MESSAGE"), type_name = sprintf(".chain.M%d", i + 1L)))
  }
  list(name = sprintf("M%d", i), field = c(next_field, list(field("v", 2L, "TYPE_INT32"))),
       extension_range = list(list(start = 100L, end = 200L)))
})
exts <- lapply(seq_len(2000) - 1L, function(i) {
  c(field(sprintf("ext%d", i), 100L, "TYPE_MESSAGE"),
    type_name = sprintf(".chain.M%d", (7L * i) %% 2000L), extendee = sprintf(".chain.M%d", i))
})
chain_pool <- proto_pool(proto_encode(
  list(file = list(list(name = "chain.proto", package = "chain", syntax = "proto2",
                        message_type = chained, extension = exts))),
  "google.protobuf.FileDescriptorSet", pool
))
m0 <- as.raw(c(0x10, 0x01))
reps <- 2e4
t_chain <- system.time(for (i in seq_len(reps)) proto_decode(m0, "chain.M0", chain_pool))[["elapsed"]]
cat(sprintf("%-46s %8.1f us\n", "proto_decode(), 2000 types + extensions, each", t_chain / reps * 1e6))

cat(sprintf("zuproto %s, upb from protobuf %s, R %s, n = %s\n",
            zuproto_info()$version, zuproto_info()$protobuf,
            getRversion(), format(n, big.mark = ",")))
rows <- data.frame(
  id = as.double(seq_len(n)), value = seq_len(n) / 7, count = seq_len(n) %% 1000L,
  flag = seq_len(n) %% 2L == 0L, name = paste0("row", seq_len(n))
)
time("encode n rows (proto_write_delimited)", stream <- proto_write_delimited(rows, "bench.Row", pool))
# 10^5 single messages for the list-input and one-at-a-time comparisons.
msgs <- lapply(seq_len(min(n, 1e5)), function(i) proto_encode(as.list(rows[i, ]), "bench.Row", pool))
t_df <- time("proto_read_delimited(), n messages", df <- proto_read_delimited(stream, "bench.Row", pool))
stopifnot(nrow(df) == n, identical(df$name[n], paste0("row", n)))
k <- length(msgs)
t_list <- time(sprintf("proto_decode_df(), %s raw vectors", format(k, big.mark = ",")),
               proto_decode_df(msgs, "bench.Row", pool))
t_one <- time(sprintf("proto_decode() + rbind, %s messages", format(k, big.mark = ",")),
              do.call(rbind.data.frame, lapply(msgs, proto_decode, "bench.Row", pool)))
cat(sprintf("proto_decode_df() is %.0fx faster than one proto_decode() per message\n", t_one / t_list))

if (requireNamespace("RProtoBuf", quietly = TRUE)) {
  proto <- tempfile(fileext = ".proto")
  writeLines(c(
    'syntax = "proto3";', "package bench;",
    "message Row { int64 id = 1; double value = 2; int32 count = 3; bool flag = 4; string name = 5; }"
  ), proto)
  RProtoBuf::readProtoFiles(proto)
  Row <- RProtoBuf::P("bench.Row")
  t_rpb <- time(sprintf("RProtoBuf read() + as.list + rbind, %s", format(k, big.mark = ",")), {
    rows_rpb <- lapply(msgs, function(m) as.list(RProtoBuf::read(Row, m)))
    do.call(rbind.data.frame, rows_rpb)
  })
  cat(sprintf("proto_decode_df() is %.0fx faster than RProtoBuf on the same %s messages\n", t_rpb / t_list, format(k, big.mark = ",")))
  m1 <- msgs[[1]]
  r1 <- RProtoBuf::read(Row, m1)
  reps <- 2e4
  t_dec <- system.time(for (i in seq_len(reps)) proto_decode(m1, "bench.Row", pool))[["elapsed"]]
  t_rdec <- system.time(for (i in seq_len(reps)) RProtoBuf::read(Row, m1))[["elapsed"]]
  x1 <- proto_decode(m1, "bench.Row", pool)
  t_enc <- system.time(for (i in seq_len(reps)) proto_encode(x1, "bench.Row", pool))[["elapsed"]]
  t_renc <- system.time(for (i in seq_len(reps)) RProtoBuf::serialize(r1, NULL))[["elapsed"]]
  cat(sprintf("one message, %s times: proto_decode() %.2f s vs read() %.2f s (%.2fx); proto_encode() %.2f s vs serialize() %.2f s (%.2fx)\n",
              format(reps, big.mark = ","), t_dec, t_rdec, t_dec / t_rdec, t_enc, t_renc, t_enc / t_renc))
} else {
  cat("RProtoBuf is not installed: no comparison.\n")
}
