Repository: VictoriaMetrics/VictoriaMetrics
Pull request #4052 (2023-04-02 17:52:09)

vmui: add apply button to the settings popup
#4013

<img width="400" alt="image" src="https://user-images.githubusercontent.com/29711459/229370033-cb3a6aa8-42a4-4b7e-b096-5810d06e7936.png">


codecov[bot]: ## [Codecov](https://codecov.io/gh/VictoriaMetrics/VictoriaMetrics/pull/4052?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics) Report
Patch coverage has no change and project coverage change: **`-0.08`** :warning:
> Comparison is base [(`06b721d`)](https://codecov.io/gh/VictoriaMetrics/VictoriaMetrics/commit/06b721dd070c6ac95d56c8e171befc077d1d1fd5?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics) 61.14% compared to head [(`55d983f`)](https://codecov.io/gh/VictoriaMetrics/VictoriaMetrics/pull/4052?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics) 61.07%.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##           master    #4052      +/-   ##
==========================================
- Coverage   61.14%   61.07%   -0.08%     
==========================================
  Files         323      323              
  Lines       58646    58646              
==========================================
- Hits        35862    35819      -43     
- Misses      20702    20734      +32     
- Partials     2082     2093      +11     
```


[see 6 files with indirect coverage changes](https://codecov.io/gh/VictoriaMetrics/VictoriaMetrics/pull/4052/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics)

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics)

</details>

[:umbrella: View full report in Codecov by Sentry](https://codecov.io/gh/VictoriaMetrics/VictoriaMetrics/pull/4052?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics).   
:loudspeaker: Do you have feedback about the report comment? [Let us know in this issue](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=VictoriaMetrics).


Patch:
diff --git a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/GlobalSettings.tsx b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/GlobalSettings.tsx
index fb7c0ec2b..4751a112e 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/GlobalSettings.tsx
+++ b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/GlobalSettings.tsx
@@ -7,7 +7,7 @@ import Modal from "../../Main/Modal/Modal";
 import "./style.scss";
 import Tooltip from "../../Main/Tooltip/Tooltip";
 import LimitsConfigurator from "./LimitsConfigurator/LimitsConfigurator";
-import { SeriesLimits } from "../../../types";
+import { Theme } from "../../../types";
 import { useCustomPanelDispatch, useCustomPanelState } from "../../../state/customPanel/CustomPanelStateContext";
 import { getAppModeEnable } from "../../../utils/app-mode";
 import classNames from "classnames";
@@ -22,7 +22,7 @@ const GlobalSettings: FC = () => {
   const { isMobile } = useDeviceDetect();
 
   const appModeEnable = getAppModeEnable();
-  const { serverUrl: stateServerUrl } = useAppState();
+  const { serverUrl: stateServerUrl, theme } = useAppState();
   const { timezone: stateTimezone } = useTimeState();
   const { seriesLimits } = useCustomPanelState();
 
@@ -31,20 +31,40 @@ const GlobalSettings: FC = () => {
   const customPanelDispatch = useCustomPanelDispatch();
 
   const [serverUrl, setServerUrl] = useState(stateServerUrl);
-  const [limits, setLimits] = useState<SeriesLimits>(seriesLimits);
+  const [limits, setLimits] = useState(seriesLimits);
   const [timezone, setTimezone] = useState(stateTimezone);
 
+  const setDefaultsValues = () => {
+    setServerUrl(stateServerUrl);
+    setLimits(seriesLimits);
+    setTimezone(stateTimezone);
+  };
+
   const [open, setOpen] = useState(false);
   const handleOpen = () => setOpen(true);
-  const handleClose = () => setOpen(false);
+  const handleClose = () => {
+    setOpen(false);
+    setDefaultsValues();
+  };
+
+  const handleCloseForce = () => {
+    setOpen(false);
+    setDefaultsValues();
+  };
+
+  const handleChangeTheme = (value: Theme) => {
+    dispatch({ type: "SET_THEME", payload: value });
+  };
 
   const handlerApply = () => {
     dispatch({ type: "SET_SERVER", payload: serverUrl });
     timeDispatch({ type: "SET_TIMEZONE", payload: timezone });
     customPanelDispatch({ type: "SET_SERIES_LIMITS", payload: limits });
+    setOpen(false);
   };
 
   useEffect(() => {
+    // the tenant selector can change the serverUrl
     if (stateServerUrl === serverUrl) return;
     setServerUrl(stateServerUrl);
   }, [stateServerUrl]);
@@ -88,10 +108,10 @@ const GlobalSettings: FC = () => {
           {!appModeEnable && (
             <div className="vm-server-configurator__input">
               <ServerConfigurator
+                stateServerUrl={stateServerUrl}
                 serverUrl={serverUrl}
                 onChange={setServerUrl}
                 onEnter={handlerApply}
-                onBlur={handlerApply}
               />
             </div>
           )}
@@ -110,9 +130,28 @@ const GlobalSettings: FC = () => {
           </div>
           {!appModeEnable && (
             <div className="vm-server-configurator__input">
-              <ThemeControl/>
+              <ThemeControl
+                theme={theme}
+                onChange={handleChangeTheme}
+              />
             </div>
           )}
+          <div className="vm-server-configurator-footer">
+            <Button
+              color="error"
+              variant="outlined"
+              onClick={handleCloseForce}
+            >
+              Cancel
+            </Button>
+            <Button
+              color="primary"
+              variant="contained"
+              onClick={handlerApply}
+            >
+              Apply
+            </Button>
+          </div>
         </div>
       </Modal>
     )}
diff --git a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/LimitsConfigurator/LimitsConfigurator.tsx b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/LimitsConfigurator/LimitsConfigurator.tsx
index d4ce7e0f7..0e898e42c 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/LimitsConfigurator/LimitsConfigurator.tsx
+++ b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/LimitsConfigurator/LimitsConfigurator.tsx
@@ -51,7 +51,7 @@ const LimitsConfigurator: FC<ServerConfiguratorProps> = ({ limits, onChange , on
     <div className="vm-limits-configurator">
       <div className="vm-server-configurator__title">
         Series limits by tabs
-        <Tooltip title="To disable limits set to 0">
+        <Tooltip title="Set to 0 to disable the limit">
           <Button
             variant="text"
             color="primary"
@@ -67,7 +67,7 @@ const LimitsConfigurator: FC<ServerConfiguratorProps> = ({ limits, onChange , on
             startIcon={<RestartIcon/>}
             onClick={handleReset}
           >
-            Reset
+            Reset limits
           </Button>
         </div>
       </div>
diff --git a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/ServerConfigurator/ServerConfigurator.tsx b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/ServerConfigurator/ServerConfigurator.tsx
index 7705911b2..6f0600aad 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/ServerConfigurator/ServerConfigurator.tsx
+++ b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/ServerConfigurator/ServerConfigurator.tsx
@@ -1,16 +1,21 @@
-import React, { FC, useState } from "preact/compat";
+import React, { FC, useEffect, useState } from "preact/compat";
 import { ErrorTypes } from "../../../../types";
 import TextField from "../../../Main/TextField/TextField";
 import { isValidHttpUrl } from "../../../../utils/url";
 
 export interface ServerConfiguratorProps {
   serverUrl: string
+  stateServerUrl: string
   onChange: (url: string) => void
   onEnter: () => void
-  onBlur: () => void
 }
 
-const ServerConfigurator: FC<ServerConfiguratorProps> = ({ serverUrl, onChange , onEnter, onBlur }) => {
+const ServerConfigurator: FC<ServerConfiguratorProps> = ({
+  serverUrl,
+  stateServerUrl,
+  onChange ,
+  onEnter
+}) => {
 
   const [error, setError] = useState("");
 
@@ -18,10 +23,13 @@ const ServerConfigurator: FC<ServerConfiguratorProps> = ({ serverUrl, onChange ,
     const value = val || "";
     onChange(value);
     setError("");
-    if (!value) setError(ErrorTypes.emptyServer);
-    if (!isValidHttpUrl(value)) setError(ErrorTypes.validServer);
   };
 
+  useEffect(() => {
+    if (!stateServerUrl) setError(ErrorTypes.emptyServer);
+    if (!isValidHttpUrl(stateServerUrl)) setError(ErrorTypes.validServer);
+  }, [stateServerUrl]);
+
   return (
     <TextField
       autofocus
@@ -30,7 +38,6 @@ const ServerConfigurator: FC<ServerConfiguratorProps> = ({ serverUrl, onChange ,
       error={error}
       onChange={onChangeServer}
       onEnter={onEnter}
-      onBlur={onBlur}
       inputmode="url"
     />
   );
diff --git a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/Timezones/style.scss b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/Timezones/style.scss
index 266172f89..512f24db3 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/Timezones/style.scss
+++ b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/Timezones/style.scss
@@ -46,7 +46,7 @@
   }
 
   &-list {
-    max-height: 200px;
+    max-height: 300px;
     background-color: $color-background-block;
     border-radius: $border-radius-medium;
     overflow: auto;
diff --git a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/style.scss b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/style.scss
index ff26ee339..9a1706615 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/style.scss
+++ b/app/vmui/packages/vmui/src/components/Configurators/GlobalSettings/style.scss
@@ -32,4 +32,17 @@
     font-weight: bold;
     margin-bottom: $padding-global;
   }
+
+  &-footer {
+    display: flex;
+    align-items: center;
+    justify-content: flex-end;
+    gap: $padding-small;
+    width: 100%;
+  }
+
+  &_mobile &-footer {
+    display: grid;
+    grid-template-columns: 1fr 1fr;
+  }
 }
diff --git a/app/vmui/packages/vmui/src/components/Configurators/ThemeControl/ThemeControl.tsx b/app/vmui/packages/vmui/src/components/Configurators/ThemeControl/ThemeControl.tsx
index c770f506a..1d2885004 100644
--- a/app/vmui/packages/vmui/src/components/Configurators/ThemeControl/ThemeControl.tsx
+++ b/app/vmui/packages/vmui/src/components/Configurators/ThemeControl/ThemeControl.tsx
@@ -1,19 +1,22 @@
 import React from "react";
 import "./style.scss";
-import { useAppDispatch, useAppState } from "../../../state/common/StateContext";
 import { Theme } from "../../../types";
 import Toggle from "../../Main/Toggle/Toggle";
 import useDeviceDetect from "../../../hooks/useDeviceDetect";
 import classNames from "classnames";
+import { FC } from "preact/compat";
+
+interface ThemeControlProps {
+  theme: Theme;
+  onChange: (val: Theme) => void
+}
 
 const options = Object.values(Theme).map(value => ({ title: value, value }));
-const ThemeControl = () => {
+const ThemeControl: FC<ThemeControlProps> = ({ theme, onChange }) => {
   const { isMobile } = useDeviceDetect();
-  const { theme } = useAppState();
-  const dispatch = useAppDispatch();
 
   const handleClickItem = (value: string) => {
-    dispatch({ type: "SET_THEME", payload: value as Theme });
+    onChange(value as Theme);
   };
 
   return (
diff --git a/app/vmui/packages/vmui/src/hooks/useFetchQuery.ts b/app/vmui/packages/vmui/src/hooks/useFetchQuery.ts
index e105bc92b..5c9dcf2c5 100644
--- a/app/vmui/packages/vmui/src/hooks/useFetchQuery.ts
+++ b/app/vmui/packages/vmui/src/hooks/useFetchQuery.ts
@@ -79,7 +79,7 @@ export const useFetchQuery = ({
     setFetchQueue([...fetchQueue, controller]);
     try {
       const isDisplayChart = displayType === "chart";
-      const seriesLimit = showAllSeries ? Infinity : stateSeriesLimits[displayType];
+      const seriesLimit = showAllSeries ? Infinity : (+stateSeriesLimits[displayType] || Infinity);
       const tempData: MetricBase[] = [];
       const tempTraces: Trace[] = [];
       let counter = 1;
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 873493529..99ff90045 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -48,6 +48,7 @@ created by v1.90.0 or newer versions. The solution is to upgrade to v1.90.0 or n
 * BUGFIX: allow using dashes and dots in environment variables names referred in config files via `%{ENV-VAR.SYNTAX}`. See [these docs](https://docs.victoriametrics.com/#environment-variables) and [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/3999).
 * BUGFIX: return back query performance scalability on hosts with big number of CPU cores. The scalability has been reduced in [v1.86.0](https://docs.victoriametrics.com/CHANGELOG.html#v1860). See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/3966).
 * BUGFIX: [MetricsQL](https://docs.victoriametrics.com/MetricsQL.html): properly convert [VictoriaMetrics historgram buckets](https://valyala.medium.com/improving-histogram-usability-for-prometheus-and-grafana-bc7e5df0e350) to Prometheus histogram buckets when VictoriaMetrics histogram contain zero buckets. Previously these buckets were ignored, and this could lead to missing Prometheus histogram buckets after the conversion. Thanks to @zklapow for [the fix](https://github.com/VictoriaMetrics/VictoriaMetrics/pull/4021).
+* BUGFIX: [vmagent](https://docs.victoriametrics.com/vmgent.html): fix CPU and memory usage spikes when files pointed by [file_sd_config](https://docs.victoriametrics.com/sd_configs.html#file_sd_configs) cannot be re-read. See [this_issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/3989).
 * BUGFIX: prevent unexpected merges on start-up when `-storage.minFreeDiskSpaceBytes` is set. See [the issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/4023).
 * BUGFIX: properly support comma-separated filters inside [retention filters](https://docs.victoriametrics.com/#retention-filters). See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/3915).
 * BUGFIX: verify response code when fetching configuration files via HTTP. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/4034).
diff --git a/docs/sd_configs.md b/docs/sd_configs.md
index 6260f20cf..b923bc910 100644
--- a/docs/sd_configs.md
+++ b/docs/sd_configs.md
@@ -94,6 +94,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_azure_subscription_id`: the subscription ID
 * `__meta_azure_tenant_id`: the tenant ID
 
+The list of discovered Azure targets is refreshed at the interval, which can be configured via `-promscrape.azureSDCheckInterval` command-line flag.
 
 ## consul_sd_configs
 
@@ -183,6 +184,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_consul_tagpresent_<tagname>`: "true" for every <tagname> tag of the target
 * `__meta_consul_tags`: the list of tags of the target joined by the `tag_separator`
 
+The list of discovered Consul targets is refreshed at the interval, which can be configured via `-promscrape.consulSDCheckInterval` command-line flag.
 
 ## digitalocean_sd_configs
 
@@ -224,6 +226,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_digitalocean_tags`: the comma-separated list of tags of the droplet
 * `__meta_digitalocean_vpc`: the id of the droplet's VPC
 
+The list of discovered DigitalOcean targets is refreshed at the interval, which can be configured via `-promscrape.digitaloceanSDCheckInterval` command-line flag.
 
 ## dns_sd_configs
 
@@ -260,6 +263,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_dns_srv_record_port`: the port field of the SRV record
 * `__meta_dns_mx_record_target`: the target field of the MX record.
 
+The list of discovered DNS targets is refreshed at the interval, which can be configured via `-promscrape.dnsSDCheckInterval` command-line flag.
 
 ## docker_sd_configs
 
@@ -315,6 +319,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_docker_port_public`: the external port if a port-mapping exists
 * `__meta_docker_port_public_ip`: the public IP if a port-mapping exists
 
+The list of discovered Docker targets is refreshed at the interval, which can be configured via `-promscrape.dockerSDCheckInterval` command-line flag.
 
 ## dockerswarm_sd_configs
 
@@ -444,6 +449,7 @@ One of the following roles can be configured to discover targets:
   * `__meta_dockerswarm_node_role`: the role of the node
   * `__meta_dockerswarm_node_status`: the status of the node
 
+The list of discovered Docker Swarm targets is refreshed at the interval, which can be configured via `-promscrape.dockerswarmSDCheckInterval` command-line flag.
 
 ## ec2_sd_configs
 
@@ -526,6 +532,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_ec2_tag_<tagkey>`: each tag value of the instance
 * `__meta_ec2_vpc_id`: the ID of the VPC in which the instance is running, if available
 
+The list of discovered EC2 targets is refreshed at the interval, which can be configured via `-promscrape.ec2SDCheckInterval` command-line flag.
 
 ## eureka_sd_configs
 
@@ -570,11 +577,11 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_eureka_app_instance_datacenterinfo_name`: the datacenter name of the app instance
 * `__meta_eureka_app_instance_datacenterinfo_metadata_<metadataname>`: the datacenter metadata
 
+The list of discovered Eureka targets is refreshed at the interval, which can be configured via `-promscrape.eurekaSDCheckInterval` command-line flag.
 
 ## file_sd_configs
 
 File-based service discovery reads a set of files with lists of targets to scrape.
-Scrape targets are automatically updated when the underlying files are changed with the interval
 
 Configuration example:
 
@@ -625,6 +632,7 @@ The following meta labels are available on discovered targets during [relabeling
 
 See the [list of integrations](https://prometheus.io/docs/operating/integrations/#file-service-discovery) with `file_sd_configs`.
 
+The list of discovered file-based targets is refreshed at the interval, which can be configured via `-promscrape.fileSDCheckInterval` command-line flag.
 
 ## gce_sd_configs
 
@@ -685,6 +693,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_gce_tags`: list of instance tags separated by tag_separator
 * `__meta_gce_zone`: the GCE zone URL in which the instance is running
 
+The list of discovered GCE targets is refreshed at the interval, which can be configured via `-promscrape.gceSDCheckInterval` command-line flag.
 
 ## http_sd_configs
 
@@ -728,6 +737,7 @@ The following meta labels are available on discovered targets during [relabeling
 
 * `__meta_url`: the URL from which the target was extracted
 
+The list of discovered HTTP-based targets is refreshed at the interval, which can be configured via `-promscrape.httpSDCheckInterval` command-line flag.
 
 ## kubernetes_sd_configs
 
@@ -945,6 +955,8 @@ One of the following `role` types can be configured to discover targets:
   * `__meta_kubernetes_ingress_scheme`: Protocol scheme of ingress, https if TLS config is set. Defaults to http.
   * `__meta_kubernetes_ingress_path`: Path from ingress spec. Defaults to `/`.
 
+The list of discovered Kuberntes targets is refreshed at the interval, which can be configured via `-promscrape.kubernetesSDCheckInterval` command-line flag.
+
 ## kuma_sd_configs
 
 Kuma service discovery config allows to fetch targets from the specified control plane `server` of [Kuma Service Mesh](https://kuma.io).
@@ -979,6 +991,8 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_kuma_service`: the name of the service associated with the proxy
 * `__meta_kuma_label_<label_name>`: each label of target given from Kuma Control Plane
 
+The list of discovered Kuma targets is refreshed at the interval, which can be configured via `-promscrape.kumaSDCheckInterval` command-line flag.
+
 ## nomad_sd_configs
 
 Nomad SD configuration allows retrieving scrape targets from [HashiCorp Nomad Services](https://www.hashicorp.com/blog/nomad-service-discovery).
@@ -1037,6 +1051,8 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_nomad_tagpresent_<tagname>`: "true" for every <tagname> tag of the target
 * `__meta_nomad_tags`: the list of tags of the target joined by the `tag_separator`
 
+The list of discovered Nomad targets is refreshed at the interval, which can be configured via `-promscrape.nomadSDCheckInterval` command-line flag.
+
 ## openstack_sd_configs
 
 OpenStack SD configuration allows retrieving scrape targets from [OpenStack Nova](https://docs.openstack.org/nova/latest/) instances.
@@ -1150,6 +1166,7 @@ One of the following `role` types can be configured to discover targets:
   * `__meta_openstack_tag_<tagkey>`: each tag value of the instance.
   * `__meta_openstack_user_id`: the user account owning the tenant.
 
+The list of discovered OpenStack targets is refreshed at the interval, which can be configured via `-promscrape.openstackSDCheckInterval` command-line flag.
 
 ## static_configs
 
@@ -1254,6 +1271,7 @@ The following meta labels are available on discovered targets during [relabeling
 * `__meta_yandexcloud_instance_private_dns_<record number>`: if configured DNS records for private IP
 * `__meta_yandexcloud_instance_public_dns_<record number>`: if configured DNS records for public IP
 
+The list of discovered Yandex Cloud targets is refreshed at the interval, which can be configured via `-promscrape.yandexcloudSDCheckInterval` command-line flag.
 
 ## scrape_configs
 
diff --git a/lib/promscrape/config.go b/lib/promscrape/config.go
index 3914c5f71..24e0dba8c 100644
--- a/lib/promscrape/config.go
+++ b/lib/promscrape/config.go
@@ -711,21 +711,11 @@ func (cfg *Config) getEurekaSDScrapeWork(prev []*ScrapeWork) []*ScrapeWork {
 
 // getFileSDScrapeWork returns `file_sd_configs` ScrapeWork from cfg.
 func (cfg *Config) getFileSDScrapeWork(prev []*ScrapeWork) []*ScrapeWork {
-	// Create a map for the previous scrape work.
-	swsMapPrev := make(map[string][]*ScrapeWork)
-	for _, sw := range prev {
-		filepath := sw.Labels.Get("__vm_filepath")
-		if len(filepath) == 0 {
-			logger.Panicf("BUG: missing `__vm_filepath` label")
-		} else {
-			swsMapPrev[filepath] = append(swsMapPrev[filepath], sw)
-		}
-	}
 	dst := make([]*ScrapeWork, 0, len(prev))
 	for _, sc := range cfg.ScrapeConfigs {
 		for j := range sc.FileSDConfigs {
 			sdc := &sc.FileSDConfigs[j]
-			dst = sdc.appendScrapeWork(dst, swsMapPrev, cfg.baseDir, sc.swc)
+			dst = sdc.appendScrapeWork(dst, cfg.baseDir, sc.swc)
 		}
 	}
 	return dst
@@ -1122,7 +1112,7 @@ func appendScrapeWorkForTargetLabels(dst []*ScrapeWork, swc *scrapeWorkConfig, t
 	return dst
 }
 
-func (sdc *FileSDConfig) appendScrapeWork(dst []*ScrapeWork, swsMapPrev map[string][]*ScrapeWork, baseDir string, swc *scrapeWorkConfig) []*ScrapeWork {
+func (sdc *FileSDConfig) appendScrapeWork(dst []*ScrapeWork, baseDir string, swc *scrapeWorkConfig) []*ScrapeWork {
 	metaLabels := promutils.GetLabels()
 	defer promutils.PutLabels(metaLabels)
 	for _, file := range sdc.Files {
@@ -1133,7 +1123,7 @@ func (sdc *FileSDConfig) appendScrapeWork(dst []*ScrapeWork, swsMapPrev map[stri
 			paths, err = filepath.Glob(pathPattern)
 			if err != nil {
 				// Do not return this error, since other files may contain valid scrape configs.
-				logger.Errorf("invalid pattern %q in `files` section: %s; skipping it", file, err)
+				logger.Errorf("invalid pattern %q in `file_sd_config->files` section of job_name=%q: %s; skipping it", file, swc.jobName, err)
 				continue
 			}
 		}
@@ -1141,13 +1131,7 @@ func (sdc *FileSDConfig) appendScrapeWork(dst []*ScrapeWork, swsMapPrev map[stri
 			stcs, err := loadStaticConfigs(path)
 			if err != nil {
 				// Do not return this error, since other paths may contain valid scrape configs.
-				if sws := swsMapPrev[path]; sws != nil {
-					// Re-use the previous valid scrape work for this path.
-					logger.Errorf("keeping the previously loaded `static_configs` from %q because of error when re-loading the file: %s", path, err)
-					dst = append(dst, sws...)
-				} else {
-					logger.Errorf("skipping loading `static_configs` from %q because of error: %s", path, err)
-				}
+				logger.Errorf("cannot load file %q for job_name=%q at `file_sd_configs`: %s; skipping this file", path, swc.jobName, err)
 				continue
 			}
 			pathShort := path
@@ -1159,7 +1143,6 @@ func (sdc *FileSDConfig) appendScrapeWork(dst []*ScrapeWork, swsMapPrev map[stri
 			}
 			metaLabels.Reset()
 			metaLabels.Add("__meta_filepath", pathShort)
-			metaLabels.Add("__vm_filepath", path) // This label is needed for internal promscrape logic
 			for i := range stcs {
 				dst = stcs[i].appendScrapeWork(dst, swc, metaLabels)
 			}
diff --git a/lib/promutils/labels.go b/lib/promutils/labels.go
index 10a254e40..f22c1552f 100644
--- a/lib/promutils/labels.go
+++ b/lib/promutils/labels.go
@@ -255,8 +255,7 @@ func (x *Labels) RemoveLabelsWithDoubleUnderscorePrefix() {
 	dst := x.Labels[:0]
 	for _, label := range src {
 		name := label.Name
-		// A hack: do not delete __vm_filepath label, since it is used by internal logic for FileSDConfig.
-		if strings.HasPrefix(name, "__") && name != "__vm_filepath" {
+		if strings.HasPrefix(name, "__") {
 			continue
 		}
 		dst = append(dst, label)


Test patch:
diff --git a/lib/promscrape/config_test.go b/lib/promscrape/config_test.go
index 40586756c..55c29f208 100644
--- a/lib/promscrape/config_test.go
+++ b/lib/promscrape/config_test.go
@@ -739,16 +739,6 @@ func TestGetFileSDScrapeWorkSuccess(t *testing.T) {
 		}
 		resetNonEssentialFields(sws)
 
-		// Remove `__vm_filepath` label, since its value depends on the current working dir.
-		for _, sw := range sws {
-			labels := sw.Labels.GetLabels()
-			for j := range labels {
-				label := &labels[j]
-				if label.Name == "__vm_filepath" {
-					label.Value = ""
-				}
-			}
-		}
 		if !reflect.DeepEqual(sws, expectedSws) {
 			t.Fatalf("unexpected scrapeWork; got\n%+v\nwant\n%+v", sws, expectedSws)
 		}
@@ -772,10 +762,9 @@ scrape_configs:
 			ScrapeTimeout:   defaultScrapeTimeout,
 			HonorTimestamps: true,
 			Labels: promutils.NewLabelsFromMap(map[string]string{
-				"__vm_filepath": "",
-				"instance":      "host1:80",
-				"job":           "foo",
-				"qwe":           "rty",
+				"instance": "host1:80",
+				"job":      "foo",
+				"qwe":      "rty",
 			}),
 			AuthConfig:      &promauth.Config{},
 			ProxyAuthConfig: &promauth.Config{},
@@ -787,10 +776,9 @@ scrape_configs:
 			ScrapeTimeout:   defaultScrapeTimeout,
 			HonorTimestamps: true,
 			Labels: promutils.NewLabelsFromMap(map[string]string{
-				"__vm_filepath": "",
-				"instance":      "host2:80",
-				"job":           "foo",
-				"qwe":           "rty",
+				"instance": "host2:80",
+				"job":      "foo",
+				"qwe":      "rty",
 			}),
 			AuthConfig:      &promauth.Config{},
 			ProxyAuthConfig: &promauth.Config{},
@@ -802,10 +790,9 @@ scrape_configs:
 			ScrapeTimeout:   defaultScrapeTimeout,
 			HonorTimestamps: true,
 			Labels: promutils.NewLabelsFromMap(map[string]string{
-				"__vm_filepath": "",
-				"instance":      "localhost:9090",
-				"job":           "foo",
-				"yml":           "test",
+				"instance": "localhost:9090",
+				"job":      "foo",
+				"yml":      "test",
 			}),
 			AuthConfig:      &promauth.Config{},
 			ProxyAuthConfig: &promauth.Config{},
diff --git a/lib/promutils/labels_test.go b/lib/promutils/labels_test.go
index c57e4dec5..83e79040c 100644
--- a/lib/promutils/labels_test.go
+++ b/lib/promutils/labels_test.go
@@ -172,6 +172,6 @@ func TestLabelsRemoveLabelsWithDoubleUnderscorePrefix(t *testing.T) {
 	}
 	f(`{}`, `{}`)
 	f(`{foo="bar"}`, `{foo="bar"}`)
-	f(`{__meta_foo="bar",a="b",__name__="foo",__vm_filepath="aa"}`, `{a="b",__vm_filepath="aa"}`)
+	f(`{__meta_foo="bar",a="b",__name__="foo",__vm_filepath="aa"}`, `{a="b"}`)
 	f(`{__meta_foo="bdffr",foo="bar",__meta_xxx="basd"}`, `{foo="bar"}`)
 }