I'm not sure why, it worked for terms bucket aggregation.
But It failed for histogram aggregation as for date histogram aggregation.
Something is wrong when s, which is supposed to be a HashMap (or possibly null), has become Long.
Could this be a bug of scripted_metric aggregation on both histogram aggregations??
GET kibana_sample_data_logs/_search?size=0
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "doc_buckets_for_date_histogram": {
      "terms": {
        "field": "agent.keyword"
      },
      "aggs": {
        "max_bytes": {
          "scripted_metric": {
            "init_script": "state.max_bytes = 0L;", 
            "map_script": """ 
              def current_bytes = doc['bytes'].getValue();
              if (current_bytes > state.max_bytes)
                {state.max_bytes = current_bytes;}
            """,
            "combine_script": "return state", 
            "reduce_script": """ 
              def max_bytes = 0L;
              for (s in states) {if (s.max_bytes > (max_bytes))
                {max_bytes = s.max_bytes;}}
              return max_bytes
            """
          }
        }   
      }
    }
  }
}
I found a similar post of several years ago left unsolved...