Compare commits

..

4 Commits

Author SHA1 Message Date
“Jayice”
d3f1c38b87 address review comments
Signed-off-by: “Jayice” <jzhou@victoriametrics.com>
2026-07-31 17:54:11 +08:00
“Jayice”
127eaa6f87 address review comments
Signed-off-by: “Jayice” <jzhou@victoriametrics.com>
2026-07-31 16:59:29 +08:00
“Jayice”
f25ee774cd polish CHANGELOG.md
Signed-off-by: “Jayice” <jzhou@victoriametrics.com>
2026-07-31 16:41:57 +08:00
“Jayice”
d89d5734cc properly parse small fractional Unix timestamps
Signed-off-by: “Jayice” <jzhou@victoriametrics.com>
2026-07-31 16:29:18 +08:00
16 changed files with 431 additions and 534 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -37,7 +37,7 @@
<meta property="og:title" content="UI for VictoriaMetrics">
<meta property="og:url" content="https://victoriametrics.com/">
<meta property="og:description" content="Explore and troubleshoot your VictoriaMetrics data">
<script type="module" crossorigin src="./assets/index-B1dXK3k7.js"></script>
<script type="module" crossorigin src="./assets/index-D5egN2id.js"></script>
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CNC7AqOf.js">
<link rel="modulepreload" crossorigin href="./assets/vendor-DwJYpOdw.js">
<link rel="stylesheet" crossorigin href="./assets/vendor-CnsZ1jie.css">

View File

@@ -26,20 +26,33 @@ func TestClusterSearchWithDisabledPerDayIndex(t *testing.T) {
defer tc.Stop()
testSearchWithDisabledPerDayIndex(tc, func(name string, disablePerDayIndex bool) apptest.PrometheusWriteQuerier {
vmstorage := tc.MustStartVmstorage("vmstorage-"+name, []string{
"-storageDataPath=" + tc.Dir() + "/vmstorage",
// Using static ports for vmstorage because random ports may cause
// changes in how data is sharded.
vmstorage1 := tc.MustStartVmstorage("vmstorage1-"+name, []string{
"-storageDataPath=" + tc.Dir() + "/vmstorage1",
"-retentionPeriod=100y",
"-httpListenAddr=127.0.0.1:61001",
"-vminsertAddr=127.0.0.1:61002",
"-vmselectAddr=127.0.0.1:61003",
fmt.Sprintf("-disablePerDayIndex=%t", disablePerDayIndex),
})
vmstorage2 := tc.MustStartVmstorage("vmstorage2-"+name, []string{
"-storageDataPath=" + tc.Dir() + "/vmstorage2",
"-retentionPeriod=100y",
"-httpListenAddr=127.0.0.1:62001",
"-vminsertAddr=127.0.0.1:62002",
"-vmselectAddr=127.0.0.1:62003",
fmt.Sprintf("-disablePerDayIndex=%t", disablePerDayIndex),
})
vminsert := tc.MustStartVminsert("vminsert-"+name, []string{
"-storageNode=" + vmstorage.VminsertAddr(),
"-storageNode=" + vmstorage1.VminsertAddr() + "," + vmstorage2.VminsertAddr(),
})
vmselect := tc.MustStartVmselect("vmselect"+name, []string{
"-storageNode=" + vmstorage.VmselectAddr(),
"-storageNode=" + vmstorage1.VmselectAddr() + "," + vmstorage2.VmselectAddr(),
"-search.maxStalenessInterval=1m",
})
return &apptest.Vmcluster{
Vmstorages: []*apptest.Vmstorage{vmstorage},
Vmstorages: []*apptest.Vmstorage{vmstorage1, vmstorage2},
Vminsert: vminsert,
Vmselect: vmselect,
}

View File

@@ -829,7 +829,7 @@ See also [minimum downtime strategy](#minimum-downtime-strategy).
## Slowness-based re-routing
By default{{% available_from "v1.149.0" %}}, `vminsert` automatically re-routes writes away from the slowest `vmstorage` node
By default{{% available_from "#" %}}, `vminsert` automatically re-routes writes away from the slowest `vmstorage` node
to preserve maximum ingestion throughput. This prevents a single slow `vmstorage` node
from throttling the entire cluster.
@@ -843,7 +843,7 @@ Disable slowness-based re-routing with `-disableRerouting=true` when keeping met
perfectly balanced across nodes or minimizing the number of [active time series](https://docs.victoriametrics.com/victoriametrics/faq/#what-is-an-active-time-series)
matters more than peak write throughput.
Slowness-based re-routing is automatically disabled{{% available_from "v1.149.0" %}} when `-replicationFactor` is greater than `1`,
Slowness-based re-routing is automatically disabled{{% available_from "#" %}} when `-replicationFactor` is greater than `1`,
because rerouting does not guarantee that replicated copies land on distinct storage nodes,
which violates the replication contract.

View File

@@ -39,8 +39,6 @@ VictoriaMetrics has the following prominent features:
* Easy and fast backups from [instant snapshots](https://medium.com/@valyala/how-victoriametrics-makes-instant-snapshots-for-multi-terabyte-time-series-data-e1f3fb0e0282)
can be done with [vmbackup](https://docs.victoriametrics.com/victoriametrics/vmbackup/) / [vmrestore](https://docs.victoriametrics.com/victoriametrics/vmrestore/) tools.
See [this article](https://medium.com/@valyala/speeding-up-backups-for-big-time-series-databases-533c1a927883) for more details.
* It supports storage and retrieval of samples with timestamps that fall within the `[1970-01-02T00:00:00.000Z, 2262-03-31T23:59:59.999Z]` time range with millisecond precision.
See [Retention](#retention) for details.
* It implements a PromQL-like query language - [MetricsQL](https://docs.victoriametrics.com/victoriametrics/metricsql/), which provides improved functionality on top of PromQL.
* It provides a global query view. Multiple Prometheus instances or any other data sources may ingest data into VictoriaMetrics. Later this data may be queried via a single query.
* It provides high performance and good vertical and horizontal scalability for both
@@ -1542,9 +1540,6 @@ It is safe to extend `-retentionPeriod` on existing data. If `-retentionPeriod`
value than before, then data outside the configured period will be eventually deleted.
VictoriaMetrics does not support indefinite retention, but you can specify an arbitrarily high duration, e.g. `-retentionPeriod=100y`.
Just keep in mind that VictoriaMetrics does not support samples with negative timestamps. Timestamps at `1970-01-01` are also not
supported because this date has a special meaning internally. It therefore rejects samples with timestamps before
`1970-01-02T00:00:00.000Z`.
By default, VictoriaMetrics doesn't accept samples with timestamps bigger than `now+2d`, e.g. 2 days in the future.
If you need accepting samples with bigger timestamps, then specify the desired "future retention" via `-futureRetention` command-line flag.
@@ -1556,9 +1551,6 @@ For example, the following command starts VictoriaMetrics, which accepts samples
/path/to/victoria-metrics -futureRetention=1y
```
VictoriaMetrics does not support stamples after `2262-03-31T23:59:59.999Z`. If the future retention includes dates after this timestamp,
the samples for those dates will be rejected.
By default, VictoriaMetrics accepts samples with timestamps as old as the configured `-retentionPeriod` allows, e.g. it accepts backfilled
historical data as long as it fits into the retention. If you need rejecting samples with historical timestamps older than the specified
duration, then specify the desired duration via the `-maxBackfillAge` command-line flag. This can be useful for limiting ingestion of

View File

@@ -26,10 +26,6 @@ See also [LTS releases](https://docs.victoriametrics.com/victoriametrics/lts-rel
## tip
## [v1.149.0](https://github.com/VictoriaMetrics/VictoriaMetrics/releases/tag/v1.149.0)
Release candidate
**Update Note 1:** `vminsert` in [VictoriaMetrics cluster](https://docs.victoriametrics.com/victoriametrics/cluster-victoriametrics/): the default value of `-disableRerouting` flag has changed from `true` to `false`, enabling [slowness-based re-routing](https://docs.victoriametrics.com/victoriametrics/cluster-victoriametrics/#slowness-based-re-routing) by default. Slowness re-routing is automatically disabled when `-replicationFactor` is greater than 1. If you rely on the old behavior, pass `-disableRerouting` command-line flag to `vminsert`. See [#11287](https://github.com/VictoriaMetrics/VictoriaMetrics/pull/11287).
**Update Note 2:** [vmsingle](https://docs.victoriametrics.com/victoriametrics/single-server-victoriametrics/) and `vmselect` in [VictoriaMetrics cluster](https://docs.victoriametrics.com/victoriametrics/cluster-victoriametrics/): the `/api/v1/admin/tsdb/delete_series`, `/tags/delSeries` endpoints now require `POST` method. Previously, it also accepted `GET` requests. If you use `GET` requests for this endpoint, update your scripts or tooling to use `POST` instead. See [#5552](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/5552).
@@ -52,6 +48,7 @@ Release candidate
* BUGFIX: [vmbackupmanager](https://docs.victoriametrics.com/victoriametrics/vmbackupmanager/): previously, `vmbackupmanager` was crashing on startup when it failed to restore backup state from remote storage, causing a crash loop. Now it logs the error and continues running, retrying the state restore before each scheduled backup. Added `vm_backup_errors_total{type="restoreState"}` metric to track backup state restore failures. See [#11217](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/11217).
* BUGFIX: [stream aggregation](https://docs.victoriametrics.com/victoriametrics/stream-aggregation/): fix incorrect [sum_samples_total](https://docs.victoriametrics.com/victoriametrics/stream-aggregation/configuration/#sum_samples_total) results when `enable_windows: true` is set. See [#11261](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/11261). Thanks to @beyond-infra for contribution.
* BUGFIX: [vmsingle](https://docs.victoriametrics.com/victoriametrics/single-server-victoriametrics/), `vmselect` in [VictoriaMetrics cluster](https://docs.victoriametrics.com/victoriametrics/cluster-victoriametrics/) and [vmctl](https://docs.victoriametrics.com/victoriametrics/vmctl/): accept scientific notation with sub-second precision (e.g. `1.784144612388E9`) for timestamp args such as `start` and `end` in `/api/v1/query_range` and `--vm-native-filter-time-start` and `--vm-native-filter-time-end` in `vmctl`. Previously, values with this pattern were rejected, which is incompatible with Prometheus. See [#11268](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/11268). Thanks to @STiFLeR7 for contribution.
* BUGFIX: [vmsingle](https://docs.victoriametrics.com/victoriametrics/single-server-victoriametrics/), `vmselect` in [VictoriaMetrics cluster](https://docs.victoriametrics.com/victoriametrics/cluster-victoriametrics/) and [vmctl](https://docs.victoriametrics.com/victoriametrics/vmctl/): properly parse small fractional Unix timestamps in timestamp args such as `start` and `end` in `/api/v1/query_range` and `--vm-native-filter-time-start` and `--vm-native-filter-time-end` in `vmctl`. Previously, fractional Unix timestamps with the integer part below `9223372` will be interpreted with the wrong unit, for example `12.0` previously will be parsed as `12000` seconds instead of `12` seconds. See [#11324](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/11324).
## [v1.148.0](https://github.com/VictoriaMetrics/VictoriaMetrics/releases/tag/v1.148.0)

View File

@@ -688,7 +688,7 @@ Extra labels can be added to metrics collected by `vmagent` via the following me
## Obfuscating label values
`vmagent` can obfuscate the values of specified labels before sending metrics to `-remoteWrite.url`
via `-remoteWrite.obfuscateLabels`{{% available_from "v1.149.0" %}}.
via `-remoteWrite.obfuscateLabels`{{% available_from "#" %}}.
This is useful when one or more `-remoteWrite.url` endpoints point to external monitoring services
outside the organization, and sensitive label values such as `ip`, `host`, `instance`, or `datacenter`

View File

@@ -480,7 +480,7 @@ Clusters here are referred to as `source` and `destination`.
To verify that `vmbackupmanager` is executing backup tasks normally, the following metrics can help:
* `vm_backup_last_success_at{type="<backup_type>"}` - unix timestamp of the last successful backup{{% available_from "v1.149.0" %}}. Remains `0` if no backup has completed successfully since startup. Check error logs and verify remote storage accessibility if this persists.
* `vm_backup_last_success_at{type="<backup_type>"}` - unix timestamp of the last successful backup{{% available_from "#" %}}. Remains `0` if no backup has completed successfully since startup. Check error logs and verify remote storage accessibility if this persists.
* `vm_backup_last_run_failed{type="<backup_type>"}` - whether the last backup task for the given backup type failed. The value `1` means the last task failed. Check the error logs of `vmbackupmanager` for the root cause
* `vm_backup_errors_total{type="<backup_type>"}` - total number of backup errors for the given backup type.

View File

@@ -1290,9 +1290,6 @@ func (pt *partition) mergeParts(pws []*partWrapper, stopCh <-chan struct{}, isFi
putBlockStreamReader(bsr)
}
if err != nil {
if mpNew != nil {
putInmemoryPart(mpNew)
}
return err
}
if mpNew != nil {
@@ -1447,8 +1444,6 @@ func (pt *partition) openCreatedPart(ph *partHeader, pws []*partWrapper, mpNew *
// The created part is empty. Remove it
if mpNew == nil {
fs.MustRemoveDir(dstPartPath)
} else {
putInmemoryPart(mpNew)
}
return nil
}

View File

@@ -1118,14 +1118,6 @@ func searchAndMerge[T any](qt *querytracer.Tracer, s *Storage, tr TimeRange, sea
qt = qt.NewChild("search indexDBs: timeRange=%v", &tr)
defer qt.Done()
var zeroValue T
if tr.MinTimestamp < minUnixMilli {
tr.MinTimestamp = minUnixMilli
}
if tr.MaxTimestamp < tr.MinTimestamp {
return zeroValue, nil
}
var idbts []indexDBWithType
ptws := s.tb.GetPartitions(tr)

View File

@@ -402,10 +402,6 @@ func TestStorageDeletePendingSeries(t *testing.T) {
defer testRemoveAll(t)
const numMonths = 10
start := time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC)
middle := start.AddDate(0, (numMonths-1)/2, 0)
end := start.AddDate(0, numMonths-1, 0)
s := MustOpenStorage(t.Name(), OpenOptions{})
var metricGroupName = []byte("metric")
@@ -460,7 +456,7 @@ func TestStorageDeletePendingSeries(t *testing.T) {
assertCountMonthsWithLabels := func(count int) {
t.Helper()
ts := start
ts := time.Unix(0, 0)
n := 0
for range numMonths {
lns, err := s.SearchLabelNames(nil, nil, TimeRange{ts.UnixMilli(), ts.UnixMilli()}, 1e5, 1e9, noDeadline)
@@ -485,7 +481,7 @@ func TestStorageDeletePendingSeries(t *testing.T) {
var search Search
defer search.MustClose()
search.Init(nil, s, []*TagFilters{tfs}, TimeRange{start.UnixMilli(), math.MaxInt64}, 1e5, noDeadline)
search.Init(nil, s, []*TagFilters{tfs}, TimeRange{0, math.MaxInt64}, 1e5, noDeadline)
n := 0
for search.NextMetricBlock() {
var b Block
@@ -502,6 +498,10 @@ func TestStorageDeletePendingSeries(t *testing.T) {
// Verify no metrics exist
assertCountRows(0)
start := time.Unix(0, 0)
middle := start.AddDate(0, (numMonths-1)/2, 0)
end := start.AddDate(0, numMonths-1, 0)
// Add some rows and flush, so next DeleteSeries() can delete them
addRows(start, middle, false)
s.DebugFlush()
@@ -3385,190 +3385,53 @@ func TestStorageQueryWithoutIndex(t *testing.T) {
testStorageSearchWithoutIndex(t, &opts)
}
func TestStorageAddRowsWithZeroDate(t *testing.T) {
func TestStorageAddRows_SamplesWithZeroDate(t *testing.T) {
defer testRemoveAll(t)
f := func(t *testing.T, disablePerDayIndex bool) {
t.Helper()
s := MustOpenStorage(t.Name(), OpenOptions{
DisablePerDayIndex: disablePerDayIndex,
})
defer s.MustClose()
mn := MetricName{MetricGroup: []byte("metric")}
mr := MetricRow{MetricNameRaw: mn.marshalRaw(nil)}
for range 10 {
mr.Timestamp = rand.Int63n(msecPerDay)
mr.Value = float64(rand.Intn(1000))
s.AddRows([]MetricRow{mr}, defaultPrecisionBits)
s.DebugFlush()
// Reset TSID cache so that insertion takes the path that involves
// checking whether the index contains metricName->TSID mapping.
s.resetAndSaveTSIDCache()
}
want := 1
firstUnixDay := TimeRange{
MinTimestamp: 0,
MaxTimestamp: msecPerDay - 1,
}
if got := s.newTimeseriesCreated.Load(); got != uint64(want) {
t.Errorf("unexpected new timeseries count: got %d, want %d", got, want)
}
if got := testCountAllMetricNames(s, firstUnixDay); got != want {
t.Errorf("unexpected metric name count: got %d, want %d", got, want)
}
if got := testCountAllMetricIDs(s, firstUnixDay); got != want {
t.Errorf("unexpected metric id count: got %d, want %d", got, want)
}
}
for _, disablePerDayIndex := range []bool{false, true} {
name := fmt.Sprintf("disablePerDayIndex=%t", disablePerDayIndex)
t.Run(name, func(t *testing.T) {
testStorageAddRowsWithZeroDate(t, disablePerDayIndex)
f(t, disablePerDayIndex)
})
}
}
func testStorageAddRowsWithZeroDate(t *testing.T, disablePerDayIndex bool) {
s := MustOpenStorage(t.Name(), OpenOptions{
DisablePerDayIndex: disablePerDayIndex,
})
defer s.MustClose()
const numDays = 4
var metricNamesAll []string
labelNamesAll := []string{"__name__", "label"}
var labelValuesAll []string
mrs := make([]MetricRow, numDays)
for day := range numDays {
metricName := fmt.Sprintf("metric_%02d", day)
labelName := fmt.Sprintf("label_%02d", day)
labelValue := fmt.Sprintf("value_%02d", day)
if day != 0 {
metricNamesAll = append(metricNamesAll, metricName)
labelNamesAll = append(labelNamesAll, labelName)
labelValuesAll = append(labelValuesAll, labelValue)
}
mn := MetricName{
MetricGroup: []byte(metricName),
Tags: []Tag{
{Key: []byte(labelName), Value: []byte("value")},
{Key: []byte("label"), Value: []byte(labelValue)},
},
}
mn.sortTags()
mrs[day].MetricNameRaw = mn.marshalRaw(nil)
mrs[day].Timestamp = int64(day * msecPerDay)
}
s.AddRows(mrs, defaultPrecisionBits)
s.DebugFlush()
if got, want := s.newTimeseriesCreated.Load(), uint64(numDays-1); got != want {
t.Fatalf("unexpected new timeseries count: got %d, want %d", got, want)
}
if got, want := s.tooSmallTimestampRows.Load(), uint64(1); got != want {
t.Fatalf("unexpected rows with too small timestamp: got %d, want %d", got, want)
}
assertMetricNames := func(tr TimeRange, want []string) {
t.Helper()
tfs := NewTagFilters()
if err := tfs.Add(nil, []byte("metric_.*"), false, true); err != nil {
t.Fatalf("unexpected error in TagFilters.Add: %v", err)
}
got, err := s.SearchMetricNames(nil, []*TagFilters{tfs}, tr, 1e9, noDeadline)
if err != nil {
t.Fatalf("SearchMetricNames(%v, %v) failed unexpectedly: %v", tfs, &tr, err)
}
for i, name := range got {
var mn MetricName
if err := mn.UnmarshalString(name); err != nil {
t.Fatalf("Could not unmarshal metric name %q: %v", name, err)
}
got[i] = string(mn.MetricGroup)
}
slices.Sort(got)
slices.Sort(want)
if diff := cmp.Diff(want, got); diff != "" {
t.Fatalf("unexpected metric names (-want, +got):\n%s", diff)
}
}
assertLabelNames := func(tr TimeRange, want []string) {
t.Helper()
tfs := NewTagFilters()
if err := tfs.Add(nil, []byte("metric_.*"), false, true); err != nil {
t.Fatalf("unexpected error in TagFilters.Add: %v", err)
}
got, err := s.SearchLabelNames(nil, []*TagFilters{tfs}, tr, 1e9, 1e9, noDeadline)
if err != nil {
t.Fatalf("SearchLabelNames(%v, %v) failed unexpectedly: %s", tfs, &tr, err)
}
slices.Sort(got)
slices.Sort(want)
if diff := cmp.Diff(want, got); diff != "" {
t.Fatalf("unexpected label names (-want, +got):\n%s", diff)
}
}
assertLabelValues := func(tr TimeRange, want []string) {
t.Helper()
tfs := NewTagFilters()
if err := tfs.Add([]byte("label"), []byte("value_.*"), false, true); err != nil {
t.Fatalf("unexpected error in TagFilters.Add: %v", err)
}
got, err := s.SearchLabelValues(nil, "label", []*TagFilters{tfs}, tr, 1e9, 1e9, noDeadline)
if err != nil {
t.Fatalf("SearchLabelValues(%v, %v) failed unexpectedly: %s", tfs, tr, err)
}
slices.Sort(got)
slices.Sort(want)
if diff := cmp.Diff(want, got); diff != "" {
t.Fatalf("unexpected label values (-want, +got):\n%s", diff)
}
}
assertData := func(tr TimeRange, want []MetricRow) {
t.Helper()
tfs := NewTagFilters()
if err := tfs.Add(nil, []byte("metric_.*"), false, true); err != nil {
t.Fatalf("TagFilters.Add() failed unexpectedly: %v", err)
}
if err := testAssertSearchResult(s, tr, tfs, want); err != nil {
t.Fatalf("Search(%v, %v) failed unexpectedly: %v", tfs, tr, err)
}
}
var tr TimeRange
// Empty time range.
// Expect empty search results
tr = TimeRange{}
assertMetricNames(tr, nil)
assertLabelNames(tr, []string{})
assertLabelValues(tr, []string{})
assertData(tr, nil)
// First day time range.
// Expect empty search results
tr = TimeRange{
MinTimestamp: 0,
MaxTimestamp: msecPerDay - 1,
}
assertMetricNames(tr, nil)
assertLabelNames(tr, []string{})
assertLabelValues(tr, []string{})
assertData(tr, nil)
// Second day time range.
tr = TimeRange{
MinTimestamp: msecPerDay,
MaxTimestamp: 2*msecPerDay - 1,
}
if disablePerDayIndex {
// Expect index search results for all days if per-day index is
// disabled.
assertMetricNames(tr, metricNamesAll)
assertLabelNames(tr, labelNamesAll)
assertLabelValues(tr, labelValuesAll)
} else {
// Expect index search results on second day only if per-day index is
// enabled.
assertMetricNames(tr, []string{"metric_01"})
assertLabelNames(tr, []string{"__name__", "label", "label_01"})
assertLabelValues(tr, []string{"value_01"})
}
assertData(tr, mrs[1:2])
// First two days time range.
// Expect results on second day only.
tr = TimeRange{
MinTimestamp: 0,
MaxTimestamp: 2*msecPerDay - 1,
}
if disablePerDayIndex {
// Expect index search results for all days if per-day index is
// disabled.
assertMetricNames(tr, metricNamesAll)
assertLabelNames(tr, labelNamesAll)
assertLabelValues(tr, labelValuesAll)
} else {
// Expect index search results on second day only if per-day index is
// enabled.
assertMetricNames(tr, []string{"metric_01"})
assertLabelNames(tr, []string{"__name__", "label", "label_01"})
assertLabelValues(tr, []string{"value_01"})
}
assertData(tr, mrs[1:2])
}
// testSearchMetricIDs returns metricIDs for the given tfss and tr.
//
// The returned metricIDs are sorted. The function panics in in case of error.

View File

@@ -429,8 +429,9 @@ func (tb *table) getMinMaxIngestionTimestamps() (int64, int64) {
func (tb *table) getMinMaxTimestampsForAge(minAgeMsecs int64) (int64, int64) {
now := int64(fasttime.UnixTimestamp() * 1000)
minTimestamp := now - minAgeMsecs
if minTimestamp < minUnixMilli {
minTimestamp = minUnixMilli
if minTimestamp < 0 {
// Negative timestamps aren't supported by the storage.
minTimestamp = 0
}
maxTimestamp := int64(maxUnixMilli)
if maxUnixMilli-now > tb.s.futureRetentionMsecs {

View File

@@ -40,6 +40,12 @@ type TimeRange struct {
MaxTimestamp int64
}
// Zero time range and zero date are used to force global index search.
var (
globalIndexTimeRange = TimeRange{}
globalIndexDate = uint64(0)
)
// DateRange returns the date range for the given time range.
func (tr *TimeRange) DateRange() (uint64, uint64) {
minDate := uint64(tr.MinTimestamp) / msecPerDay
@@ -111,29 +117,10 @@ func (tr *TimeRange) contains(timestamp int64) bool {
return tr.MinTimestamp <= timestamp && timestamp <= tr.MaxTimestamp
}
// Zero time range and zero date are used to force global index search.
var (
globalIndexDate = uint64(0)
globalIndexTimeRange = TimeRange{}
)
const (
msecPerDay = 24 * 3600 * 1000
msecPerHour = 3600 * 1000
// minUnixMilli is the min millisecond that is allowed to be used as the
// sample timestamp.
//
// It corresponds to the first millisecond of the second day of the Unix
// Epoch, i.e. 1970-01-02T00:00:00.000Z.
//
// The first day of the Unix Epoch is reserved: zero date and zero time
// range are used for indicating that the the global index search is
// required. See globalIndexDate and globalIndexTimeRange above.
//
// Negative timestamps aren't supported.
minUnixMilli = msecPerDay
// maxUnixMilli is the max millisecond that is allowed to be used as the
// sample timestamp.
//
@@ -143,6 +130,6 @@ const (
// time.UnixMicro(math.MaxInt64/1000) == 2262-04-11 23:47:16.854775 UTC.
//
// Round it to the last millisecond of the last complete partition:
// 2262-03-31T23:59:59.999Z.
// 2262-03-31 23:59:59.999 UTC.
maxUnixMilli = 9222422399999
)

View File

@@ -148,11 +148,11 @@ func TryParseUnixTimestamp(s string) (int64, bool) {
if !ok {
return 0, false
}
n, ok := tryParseScientificNumberForUnixTimestamp(s[:expIdx], decimalExp)
n, ok := tryParseScientificUnixTimestamp(s[:expIdx], decimalExp)
if !ok {
return 0, false
}
return getUnixTimestampNanoseconds(n), true
return n, true
}
dotIdx := strings.IndexByte(s, '.')
@@ -168,22 +168,11 @@ func TryParseUnixTimestamp(s string) (int64, bool) {
// The timestamp is fractional.
intStr := s[:dotIdx]
fracStr := s[dotIdx+1:]
n, ok := tryParseFractionalNumberForUnixTimestamp(intStr, fracStr)
n, ok := tryParseFractionalUnixTimestamp(intStr, fracStr)
if !ok {
return 0, false
}
// Adjust the n to multiples of thousands, since this is expected by getUnixTimestampNanoseconds.
decimalExp := len(fracStr)
for decimalExp%3 != 0 {
if n >= 0 && n > math.MaxInt64/10 || n < 0 && n < math.MinInt64/10 {
return 0, false
}
n *= 10
decimalExp++
}
return getUnixTimestampNanoseconds(n), true
return n, true
}
func getExpIndex(s string) int {
@@ -196,14 +185,18 @@ func getExpIndex(s string) int {
return -1
}
func tryParseScientificNumberForUnixTimestamp(s string, decimalExp int64) (int64, bool) {
func tryParseScientificUnixTimestamp(s string, decimalExp int64) (int64, bool) {
dotIdx := strings.IndexByte(s, '.')
if dotIdx < 0 {
n, ok := tryParseInt64(s)
if !ok {
return 0, false
}
return multiplyByDecimalExp(n, decimalExp)
n, ok = multiplyByDecimalExp(n, decimalExp)
if !ok {
return 0, false
}
return getUnixTimestampNanoseconds(n), true
}
if decimalExp < 0 {
@@ -214,31 +207,32 @@ func tryParseScientificNumberForUnixTimestamp(s string, decimalExp int64) (int64
intStr := s[:dotIdx]
fracStr := s[dotIdx+1:]
n, ok := tryParseFractionalNumberForUnixTimestamp(intStr, fracStr)
if !ok {
return 0, false
}
if decimalExp >= int64(len(fracStr)) {
// The exponent shifts the decimal point past every fractional digit,
// so the value is an integer number of seconds (or coarser).
n, ok := tryParseDecimalMantissaAsInt(intStr, fracStr)
if !ok {
return 0, false
}
decimalExp -= int64(len(fracStr))
return multiplyByDecimalExp(n, decimalExp)
n, ok = multiplyByDecimalExp(n, decimalExp)
if !ok {
return 0, false
}
return getUnixTimestampNanoseconds(n), true
}
// The exponent leaves fractional digits, e.g. 1.784144612388E9 == 1784144612.388
// Pad n as plain fractional timestamps do.
fracDigits := int64(len(fracStr)) - decimalExp
for fracDigits%3 != 0 {
if n >= 0 && n > math.MaxInt64/10 || n < 0 && n < math.MinInt64/10 {
return 0, false
}
n *= 10
fracDigits++
if decimalExp >= int64(len(decimalMultipliers)) {
return 0, false
}
return n, true
decimalExpInt := int(decimalExp)
intStr = s[:dotIdx] + fracStr[:decimalExpInt]
fracStr = fracStr[decimalExpInt:]
return tryParseFractionalUnixTimestamp(intStr, fracStr)
}
func tryParseFractionalNumberForUnixTimestamp(intStr, fracStr string) (int64, bool) {
func tryParseDecimalMantissaAsInt(intStr, fracStr string) (int64, bool) {
n, ok := tryParseInt64(intStr)
if !ok {
return 0, false
@@ -270,6 +264,49 @@ func tryParseFractionalNumberForUnixTimestamp(intStr, fracStr string) (int64, bo
return num, true
}
func tryParseFractionalUnixTimestamp(intStr, fracStr string) (int64, bool) {
n, ok := tryParseInt64(intStr)
if !ok {
return 0, false
}
frac, ok := tryParseInt64(fracStr)
if !ok {
return 0, false
}
decimalExp := len(fracStr)
if decimalExp == 0 || decimalExp >= len(decimalMultipliers) {
return 0, false
}
multiplier := getUnixTimestampNanosecondsMultiplier(n)
if multiplier == 1 && frac != 0 {
return 0, false
}
n *= multiplier
scale := decimalMultipliers[decimalExp]
var fracNsec int64
if scale >= multiplier {
divisor := scale / multiplier
// Reject fractional values that cannot be represented as a whole number of nanoseconds.
// e.g. 1700000000000000000.1 ns
if frac%divisor != 0 {
return 0, false
}
fracNsec = frac / divisor
} else {
fracNsec = frac * (multiplier / scale)
}
if strings.HasPrefix(intStr, "-") {
if n < math.MinInt64+fracNsec {
return 0, false
}
return n - fracNsec, true
}
if n > math.MaxInt64-fracNsec {
return 0, false
}
return n + fracNsec, true
}
func multiplyByDecimalExp(n int64, decimalExp int64) (int64, bool) {
if decimalExp < 0 {
return 0, false
@@ -302,20 +339,24 @@ const (
)
func getUnixTimestampNanoseconds(n int64) int64 {
return n * getUnixTimestampNanosecondsMultiplier(n)
}
func getUnixTimestampNanosecondsMultiplier(n int64) int64 {
if n <= maxValidSecond && n >= minValidSecond {
// The timestamp is in seconds.
return n * 1e9
return 1e9
}
if n <= maxValidMilli && n >= minValidMilli {
// The timestamp is in milliseconds.
return n * 1e6
return 1e6
}
if n <= maxValidMicro && n >= minValidMicro {
// The timestamp is in microseconds.
return n * 1e3
return 1e3
}
// The timestamp is in nanoseconds
return n
return 1
}
func tryParseInt64(s string) (int64, bool) {

View File

@@ -24,62 +24,74 @@ func TestTryParseUnixTimestamp_Success(t *testing.T) {
f("0", 0)
// nanoseconds
f("-1234567890123456789", -1234567890123456789)
f("1234567890123456789", 1234567890123456789)
f("1234567890123456.789", 1234567890123456789)
f("-1234567890123456789", -1234567890_123_456_789)
f("1234567890123456789", 1234567890_123_456_789)
f("1234567890123456.789", 1234567890_123_456_789)
// microseconds
f("-1234567890123456", -1234567890123456000)
f("1234567890123456", 1234567890123456000)
f("1234567890123456.789", 1234567890123456789)
f("-1234567890123456", -1234567890_123_456_000)
f("1234567890123456", 1234567890_123_456_000)
f("1234567890123456.789", 1234567890_123_456_789)
f("12345678901234.5000", 12345678_901_234_500)
// milliseconds
f("-1234567890123", -1234567890123000000)
f("1234567890123", 1234567890123000000)
f("1234567890123.456", 1234567890123456000)
f("-1234567890123", -1234567890_123_000_000)
f("1234567890123", 1234567890_123_000_000)
f("1234567890123.456", 1234567890_123_456_000)
// seconds
f("-1234567890", -1234567890000000000)
f("1234567890", 1234567890000000000)
f("1234567890.123456789", 1234567890123456789)
f("1234567890.12345678", 1234567890123456780)
f("1234567890.1234567", 1234567890123456700)
f("-1234567890.123456", -1234567890123456000)
f("-1234567890.12345", -1234567890123450000)
f("-1234567890.1234", -1234567890123400000)
f("-1234567890.123", -1234567890123000000)
f("-1234567890.12", -1234567890120000000)
f("-1234567890.1", -1234567890100000000)
f("-1234567890", -1234567890_000_000_000)
f("1234567890", 1234567890_000_000_000)
f("1234567890.123456789", 1234567890_123_456_789)
f("1234567890.12345678", 1234567890_123_456_780)
f("1234567890.1234567", 1234567890_123_456_700)
f("-1234567890.123456", -1234567890_123_456_000)
f("-1234567890.12345", -1234567890_123_450_000)
f("-1234567890.1234", -1234567890_123_400_000)
f("-1234567890.123", -1234567890_123_000_000)
f("-1234567890.12", -1234567890_120_000_000)
f("-1234567890.1", -1234567890_100_000_000)
f("12", 12_000_000_000)
f("12.0", 12_000_000_000)
f("12.34", 12_340_000_000)
f("12.999999999000000000", 12_999_999_999)
f("-12", -12_000_000_000)
f("-12.34", -12_340_000_000)
f("8223372", 8223372_000_000_000)
f("8223372.0", 8223372_000_000_000)
f("1700000000", 1700000000_000_000_000)
f("1700000000.0", 1700000000_000_000_000)
// scientific notation
f("1e9", 1000000000000000000)
f("1.234e9", 1234000000000000000)
f("-1.23456789e9", -1234567890000000000)
f("1.234567890123456789e18", 1234567890123456789)
f("-1.234567890123456789e18", -1234567890123456789)
f("0.23456789e9", 234567890000000000)
f("123.456789123e9", 123456789123000000)
f("-1234.5678912e9", -1234567891200000000)
f("123.678912e7", 1236789120000000000)
f("1.23e7", 12300000000000000)
f("1.23e6", 1230000000000000)
f("1.23e5", 123000000000000)
f("1.23e4", 12300000000000)
f("1.23e3", 1230000000000)
f("1.23e2", 123000000000)
f("1.2e1", 12000000000)
f("1123.456789123456789E15", 1123456789123456789)
f("1e9", 1000000000_000_000_000)
f("1.234e9", 1234000000_000_000_000)
f("-1.23456789e9", -1234567890_000_000_000)
f("1.234567890123456789e18", 1234567890_123_456_789)
f("-1.234567890123456789e18", -1234567890_123_456_789)
f("0.23456789e9", 234567890_000_000_000)
f("123.456789123e9", 123456789_123_000_000)
f("-1234.5678912e9", -1234567891_200_000_000)
f("123.678912e7", 1236789120_000_000_000)
f("1.23e7", 12300000_000_000_000)
f("1.23e6", 1230000_000_000_000)
f("1.23e5", 123000_000_000_000)
f("1.23e4", 12300_000_000_000)
f("1.23e3", 1230_000_000_000)
f("1.23e2", 123_000_000_000)
f("1.2e1", 12_000_000_000)
f("1123.456789123456789E15", 1123456789_123_456_789)
// scientific notation with sub-second precision, i.e. more fractional digits
// than the exponent shifts (https://github.com/VictoriaMetrics/VictoriaMetrics/issues/11268).
// These must match the equivalent plain fractional form.
f("1.784144612388E9", 1784144612388000000) // == 1784144612.388
f("1.784144612388e9", 1784144612388000000)
f("-1.784144612388e9", -1784144612388000000)
f("1.5000000005e9", 1500000000500000000) // == 1500000000.5
f("1.23456789e9", 1234567890000000000) // exponent consumes all frac digits (integer result)
f("1.23e1", 12300000000000) // == 12.3
f("1.234e0", 1234000000000) // == 1.234
f("1.784144612388E9", 1784144612_388_000_000) // == 1784144612.388
f("1.784144612388e9", 1784144612_388_000_000)
f("-1.784144612388e9", -1784144612_388_000_000)
f("1.5000000005e9", 1500000000_500_000_000) // == 1500000000.5
f("1.23456789e9", 1234567890_000_000_000) // exponent consumes all frac digits (integer result)
f("1.23e1", 12_300_000_000) // == 12.3
f("1.234e0", 1_234_000_000) // == 1.234
f("1234567890123456789.0e0", 1234567890_123_456_789)
}
func TestTryParseUnixTimestamp_Failure(t *testing.T) {
@@ -129,6 +141,10 @@ func TestTryParseUnixTimestamp_Failure(t *testing.T) {
// negative decimal exponent
f("1E-1")
f("1.3e-123456789090123")
// fractional part for nanoseconds
f("1234567890123456789.1")
f("1234567890123456789.1e0")
}
func TestParseTimeAtSuccess(t *testing.T) {
@@ -146,27 +162,27 @@ func TestParseTimeAtSuccess(t *testing.T) {
now := time.Now().UnixNano()
// unix timestamp in seconds
f("1562529662", now, 1562529662*1e9)
f("1562529662.6", now, 1562529662600*1e6)
f("1562529662.67", now, 1562529662670*1e6)
f("1562529662.678", now, 1562529662678*1e6)
f("1562529662.678123", now, 1562529662678123*1e3)
f("1562529662.678123456", now, 1562529662678123456)
f("1562529662", now, 1562529662_000_000_000)
f("1562529662.6", now, 1562529662_600_000_000)
f("1562529662.67", now, 1562529662_670_000_000)
f("1562529662.678", now, 1562529662_678_000_000)
f("1562529662.678123", now, 1562529662_678_123_000)
f("1562529662.678123456", now, 1562529662_678_123_456)
// unix timestamp in milliseconds
f("1562529662678", now, 1562529662678*1e6)
f("1562529662678.9", now, 1562529662678900*1e3)
f("1562529662678.901", now, 1562529662678901*1e3)
f("1562529662678.901324", now, 1562529662678901324)
f("1562529662678", now, 1562529662_678_000_000)
f("1562529662678.9", now, 1562529662_678_900_000)
f("1562529662678.901", now, 1562529662_678_901_000)
f("1562529662678.901324", now, 1562529662_678_901_324)
// unix timestamp in microseconds
f("1562529662678901", now, 1562529662678901*1e3)
f("1562529662678901.3", now, 1562529662678901300)
f("1562529662678901.32", now, 1562529662678901320)
f("1562529662678901.321", now, 1562529662678901321)
f("1562529662678901", now, 1562529662_678_901_000)
f("1562529662678901.3", now, 1562529662_678_901_300)
f("1562529662678901.32", now, 1562529662_678_901_320)
f("1562529662678901.321", now, 1562529662_678_901_321)
// unix timestamp in nanoseconds
f("1562529662678901234", now, 1562529662678901234)
f("1562529662678901234", now, 1562529662_678_901_234)
// duration relative to the current time
f("now", now, now)
@@ -175,7 +191,7 @@ func TestParseTimeAtSuccess(t *testing.T) {
// negative duration relative to the current time
f("-5m", now, now-5*60*1e9)
f("-123", now, now-123*1e9)
f("-123.456", now, now-123456*1e6)
f("-123.456", now, now-123_456*1e6)
f("now-1h5m", now, now-(3600+5*60)*1e9)
// Year
@@ -209,9 +225,9 @@ func TestParseTimeAtSuccess(t *testing.T) {
f("2023-05-20T04:57:43-02:30", now, 1.684567663e+09*1e9)
// milliseconds
f("2023-05-20T04:57:43.123Z", now, 1684558663123000000)
f("2023-05-20T04:57:43.123456789+02:30", now, 1684549663123456789)
f("2023-05-20T04:57:43.123456789-02:30", now, 1684567663123456789)
f("2023-05-20T04:57:43.123Z", now, 1684558663_123_000_000)
f("2023-05-20T04:57:43.123456789+02:30", now, 1684549663_123_456_789)
f("2023-05-20T04:57:43.123456789-02:30", now, 1684567663_123_456_789)
}
func TestParseTimeAtLimits(t *testing.T) {