ronantakizawa/codereview-bench huggingface dataset:
Repository: syncthing/syncthing
File: lib/model/model_test.go (Go)

Code before:
	wcfg, fcfg := tmpDefaultWrapper()
	m := setupModel(wcfg)
	defer cleanupModel(m)

	numFiles := 20

	ffs := fcfg.Filesystem()
	for i := 0; i < numFiles; i++ {
		v := fmt.Sprintf("%d", i)
		must(t, writeFile(ffs, v, []byte(v), 0644))
	}

	m.ScanFolders()

	// Reach info the model, grab the fileset.

	m.fmut.RLock()
	fset := m.folderFiles["default"]
	m.fmut.RUnlock()

	count := 0
	snap := fset.Snapshot()
	snap.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
		count++
		return true
	})
	snap.Release()

	if count != numFiles {
		t.Errorf("Unexpected count: %d != %d", count, numFiles)
	}

	// Modify all the files, other than the ones we expect to rename
	for i := 0; i < numFiles; i++ {
		if i == 3 || i == 17 || i == 16 || i == 4 {
			continue
		}
		v := fmt.Sprintf("%d", i)
		must(t, writeFile(ffs, v, []byte(v+"-new"), 0644))
	}
	// Rename
	must(t, ffs.Rename("3", "17"))
	must(t, ffs.Rename("16", "4"))

	// Scan
	m.ScanFolders()

	// Verify sequence of a appearing is followed by c disappearing.
	snap = fset.Snapshot()
	defer snap.Release()


Review comment (suggestion):
```suggestion
	count := 0
	snap := dbSnapshot(t, m, "default")
```

Code after:
		count++
		return true
	})
	snap.Release()

	if count != numFiles {
		t.Errorf("Unexpected count: %d != %d", count, numFiles)
	}

	// Modify all the files, other than the ones we expect to rename
	for i := 0; i < numFiles; i++ {
		if i == 3 || i == 17 || i == 16 || i == 4 {
			continue
		}
		v := fmt.Sprintf("%d", i)
		must(t, writeFile(ffs, v, []byte(v+"-new"), 0644))
	}
	// Rename
	must(t, ffs.Rename("3", "17"))
	must(t, ffs.Rename("16", "4"))

	// Scan
	m.ScanFolders()

	// Verify sequence of a appearing is followed by c disappearing.
	snap = dbSnapshot(t, m, "default")
	defer snap.Release()

	var firstExpectedSequence int64
	var secondExpectedSequence int64
	failed := false
	snap.WithHaveSequence(0, func(i db.FileIntf) bool {
		t.Log(i)
		if i.FileName() == "17" {
			firstExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "4" {
			secondExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "3" {
			failed = i.SequenceNo() != firstExpectedSequence || failed
		}
		if i.FileName() == "16" {
			failed = i.SequenceNo() != secondExpectedSequence || failed
		}
		return true
	})
	if failed {
		t.Fail()
	}
}
Repository: syncthing/syncthing
File: lib/model/model_test.go (Go)

Code before:
		count++
		return true
	})
	snap.Release()

	if count != numFiles {
		t.Errorf("Unexpected count: %d != %d", count, numFiles)
	}

	// Modify all the files, other than the ones we expect to rename
	for i := 0; i < numFiles; i++ {
		if i == 3 || i == 17 || i == 16 || i == 4 {
			continue
		}
		v := fmt.Sprintf("%d", i)
		must(t, writeFile(ffs, v, []byte(v+"-new"), 0644))
	}
	// Rename
	must(t, ffs.Rename("3", "17"))
	must(t, ffs.Rename("16", "4"))

	// Scan
	m.ScanFolders()

	// Verify sequence of a appearing is followed by c disappearing.
	snap = fset.Snapshot()
	defer snap.Release()

	var firstExpectedSequence int64
	var secondExpectedSequence int64
	failed := false
	snap.WithHaveSequence(0, func(i db.FileIntf) bool {
		t.Log(i)
		if i.FileName() == "17" {
			firstExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "4" {
			secondExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "3" {
			failed = i.SequenceNo() != firstExpectedSequence || failed
		}
		if i.FileName() == "16" {
			failed = i.SequenceNo() != secondExpectedSequence || failed
		}
		return true
	})
	if failed {
		t.Fail()
	}
}

Review comment (suggestion):
```suggestion
	snap = dbSnapshot(t, m, "default")
```

Code after:

	// Verify sequence of a appearing is followed by c disappearing.
	snap = dbSnapshot(t, m, "default")
	defer snap.Release()

	var firstExpectedSequence int64
	var secondExpectedSequence int64
	failed := false
	snap.WithHaveSequence(0, func(i db.FileIntf) bool {
		t.Log(i)
		if i.FileName() == "17" {
			firstExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "4" {
			secondExpectedSequence = i.SequenceNo() + 1
		}
		if i.FileName() == "3" {
			failed = i.SequenceNo() != firstExpectedSequence || failed
		}
		if i.FileName() == "16" {
			failed = i.SequenceNo() != secondExpectedSequence || failed
		}
		return true
	})
	if failed {
		t.Fail()
	}
}

func TestBlockListMap(t *testing.T) {
	wcfg, fcfg := tmpDefaultWrapper()
	m := setupModel(wcfg)
	defer cleanupModel(m)

	ffs := fcfg.Filesystem()
	must(t, writeFile(ffs, "one", []byte("content"), 0644))
	must(t, writeFile(ffs, "two", []byte("content"), 0644))
	must(t, writeFile(ffs, "three", []byte("content"), 0644))
	must(t, writeFile(ffs, "four", []byte("content"), 0644))
	must(t, writeFile(ffs, "five", []byte("content"), 0644))

	m.ScanFolders()

	snap := dbSnapshot(t, m, "default")
	defer snap.Release()
	fi, ok := snap.Get(protocol.LocalDeviceID, "one")
	if !ok {
		t.Error("failed to find existing file")
	}
	var paths []string
Repository: syncthing/syncthing
File: lib/db/set.go (Go)

Code before:
	})

	return files
}

// RemoteNeedFolderFiles returns paginated list of currently needed files in
// progress, queued, and to be queued on next puller iteration, as well as the
// total number of files currently needed.
func (s *Snapshot) RemoteNeedFolderFiles(device protocol.DeviceID, page, perpage int) []FileInfoTruncated {
	files := make([]FileInfoTruncated, 0, perpage)
	skip := (page - 1) * perpage
	get := perpage
	s.WithNeedTruncated(device, func(f FileIntf) bool {
		if skip > 0 {
			skip--
			return true
		}
		files = append(files, f.(FileInfoTruncated))
		get--
		return get > 0
	})
	return files
}

func (s *Snapshot) WithBlocksHash(hash []byte, iterator Iterator) error {
	key, err := s.t.keyer.GenerateBlockListMapKey(nil, []byte(s.folder), hash, nil)
	if err != nil {
		return err
	}

	iter, err := s.t.NewPrefixIterator(key)
	if err != nil {
		return err
	}
	defer iter.Release()

	for iter.Next() {
		file := string(s.t.keyer.NameFromBlockListMapKey(iter.Key()))
		fi, ok := s.Get(protocol.LocalDeviceID, file)
		if !ok {
			continue
		}

		if !bytes.Equal(fi.BlocksHash, hash) {
			// Perhaps should be at least info?
			l.Debugf("Mismatching block map list hashes: got %x expected %x", fi.BlocksHash, hash)
			continue
		}

		if fi.IsDeleted() || fi.IsInvalid() || fi.IsIgnored() || fi.IsUnsupported() || fi.IsDirectory() || fi.IsSymlink() {
			l.Debugf("Found something of unexpected type in block map list: %s", fi)

Review comment (bug):
It would be more consistent with all the other iterators if the implementation lived in `transactions.go` and has the usual ```Debugf(`%s WithBlocksHash ...``` logging here.

Code after:
		}
		files = append(files, f.(FileInfoTruncated))
		get--
		return get > 0
	})
	return files
}

func (s *Snapshot) WithBlocksHash(hash []byte, fn Iterator) {
	l.Debugf(`%s WithBlocksHash("%x")`, s.folder, hash)
	if err := s.t.withBlocksHash([]byte(s.folder), hash, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
		panic(err)
	}
}

func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
	return s.meta.Sequence(device)
}

func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
	id, err := s.db.getIndexID(device[:], []byte(s.folder))
	if backend.IsClosed(err) {
		return 0
	} else if err != nil {
		panic(err)
	}
	if id == 0 && device == protocol.LocalDeviceID {
		// No index ID set yet. We create one now.
		id = protocol.NewIndexID()
		err := s.db.setIndexID(device[:], []byte(s.folder), id)
		if backend.IsClosed(err) {
			return 0
		} else if err != nil {
			panic(err)
		}
	}
	return id
}

func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
	if device == protocol.LocalDeviceID {
		panic("do not explicitly set index ID for local device")
	}
	if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
		panic(err)
	}
}

func (s *FileSet) MtimeFS() *fs.MtimeFS {
	prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
	if backend.IsClosed(err) {
Repository: syncthing/syncthing
File: lib/db/lowlevel.go (Go)

Code before:
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k2.WithoutName()); err != nil {
		return err
	}

	// Remove all needs related to the folder
	k3, err := db.keyer.GenerateNeedFileKey(nil, folder, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k3.WithoutName()); err != nil {
		return err
	}

	// Remove the blockmap of the folder
	k4, err := db.keyer.GenerateBlockMapKey(nil, folder, nil, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k4.WithoutHashAndName()); err != nil {
		return err
	}

	k5, err := db.keyer.GenerateBlockListMapKey(nil, folder, nil, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k5.WithoutHashAndName()); err != nil {
		return err
	}

	return t.Commit()
}

func (db *Lowlevel) dropDeviceFolder(device, folder []byte, meta *metadataTracker) error {
	db.gcMut.RLock()
	defer db.gcMut.RUnlock()

	t, err := db.newReadWriteTransaction()
	if err != nil {
		return err
	}
	defer t.close()

	key, err := db.keyer.GenerateDeviceFileKey(nil, folder, device, nil)
	if err != nil {
		return err
	}
	dbi, err := t.NewPrefixIterator(key)

Review comment (suggestion):
Is there a reason to not reuse byte slices in this function (except that it's already like that now)? Not asking to have it changed, just curious because I don't see it and if there is a reason, I'd like to know in case I ever touch this :)

Code after:
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k2.WithoutName()); err != nil {
		return err
	}

	// Remove all needs related to the folder
	k3, err := db.keyer.GenerateNeedFileKey(k2, folder, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k3.WithoutName()); err != nil {
		return err
	}

	// Remove the blockmap of the folder
	k4, err := db.keyer.GenerateBlockMapKey(k3, folder, nil, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k4.WithoutHashAndName()); err != nil {
		return err
	}

	k5, err := db.keyer.GenerateBlockListMapKey(k4, folder, nil, nil)
	if err != nil {
		return err
	}
	if err := t.deleteKeyPrefix(k5.WithoutHashAndName()); err != nil {
		return err
	}

	return t.Commit()
}

func (db *Lowlevel) dropDeviceFolder(device, folder []byte, meta *metadataTracker) error {
	db.gcMut.RLock()
	defer db.gcMut.RUnlock()

	t, err := db.newReadWriteTransaction()
	if err != nil {
		return err
	}
	defer t.close()

	key, err := db.keyer.GenerateDeviceFileKey(nil, folder, device, nil)
	if err != nil {
		return err
	}
	dbi, err := t.NewPrefixIterator(key)
Repository: syncthing/syncthing
File: lib/db/set.go (Go)

Code before:
		return get > 0
	})
	return files
}

func (s *Snapshot) WithBlocksHash(hash []byte, iterator Iterator) error {
	key, err := s.t.keyer.GenerateBlockListMapKey(nil, []byte(s.folder), hash, nil)
	if err != nil {
		return err
	}

	iter, err := s.t.NewPrefixIterator(key)
	if err != nil {
		return err
	}
	defer iter.Release()

	for iter.Next() {
		file := string(s.t.keyer.NameFromBlockListMapKey(iter.Key()))
		fi, ok := s.Get(protocol.LocalDeviceID, file)
		if !ok {
			continue
		}

		if !bytes.Equal(fi.BlocksHash, hash) {
			// Perhaps should be at least info?
			l.Debugf("Mismatching block map list hashes: got %x expected %x", fi.BlocksHash, hash)
			continue
		}

		if fi.IsDeleted() || fi.IsInvalid() || fi.IsIgnored() || fi.IsUnsupported() || fi.IsDirectory() || fi.IsSymlink() {
			l.Debugf("Found something of unexpected type in block map list: %s", fi)
			continue
		}

		if !iterator(fi) {
			break
		}
	}

	return iter.Error()
}

func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
	return s.meta.Sequence(device)
}

func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
	id, err := s.db.getIndexID(device[:], []byte(s.folder))
	if backend.IsClosed(err) {
		return 0

Review comment (bug):
I'd say either we are confident this doesn't happen, then leave it at debug (or don't even check), or make it a warning to get reports asap (and maybe even create a repair mechanism like with sequences, but 🤮).

Code after:
func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
	id, err := s.db.getIndexID(device[:], []byte(s.folder))
	if backend.IsClosed(err) {
		return 0
	} else if err != nil {
		panic(err)
	}
	if id == 0 && device == protocol.LocalDeviceID {
		// No index ID set yet. We create one now.
		id = protocol.NewIndexID()
		err := s.db.setIndexID(device[:], []byte(s.folder), id)
		if backend.IsClosed(err) {
			return 0
		} else if err != nil {
			panic(err)
		}
	}
	return id
}

func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
	if device == protocol.LocalDeviceID {
		panic("do not explicitly set index ID for local device")
	}
	if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
		panic(err)
	}
}

func (s *FileSet) MtimeFS() *fs.MtimeFS {
	prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
	if backend.IsClosed(err) {
		return nil
	} else if err != nil {
		panic(err)
	}
	kv := NewNamespacedKV(s.db, string(prefix))
	return fs.NewMtimeFS(s.fs, kv)
}

func (s *FileSet) ListDevices() []protocol.DeviceID {
	return s.meta.devices()
}

func (s *FileSet) RepairSequence() (int, error) {
	s.updateAndGCMutexLock() // Ensures consistent locking order
	defer s.updateMutex.Unlock()
	defer s.db.gcMut.RUnlock()
	return s.db.repairSequenceGCLocked(s.folder, s.meta)
}
Repository: syncthing/syncthing
File: lib/db/transactions.go (Go)

Code before:
	}
	if err != nil {
		return err
	}
	return dbi.Error()
}

func (t *readOnlyTransaction) withBlocksHash(folder, hash []byte, iterator Iterator) error {
	key, err := t.keyer.GenerateBlockListMapKey(nil, folder, hash, nil)
	if err != nil {
		return err
	}

	iter, err := t.NewPrefixIterator(key)
	if err != nil {
		return err
	}
	defer iter.Release()

	for iter.Next() {
		file := string(t.keyer.NameFromBlockListMapKey(iter.Key()))
		f, ok, err := t.getFile(folder, protocol.LocalDeviceID[:], []byte(osutil.NormalizedFilename(file)))
		if backend.IsClosed(err) {
			return err
		} else if err != nil {
			panic(err)
		}
		if !ok {
			continue
		}
		f.Name = osutil.NativeFilename(f.Name)

		if !bytes.Equal(f.BlocksHash, hash) {
			l.Warnf("Mismatching block map list hashes: got %x expected %x", f.BlocksHash, hash)
			continue
		}

		if f.IsDeleted() || f.IsInvalid() || f.IsDirectory() || f.IsSymlink() {
			l.Debugf("Found something of unexpected type in block map list: %s", f)
			continue
		}

		if !iterator(f) {
			break
		}
	}

	return iter.Error()
}

func (t *readOnlyTransaction) availability(folder, file []byte) ([]protocol.DeviceID, error) {

Review comment (suggestion):
```suggestion
```

Errors are already filtered in the calling func in set.go.

Code after:
			return err
		}

		f, ok, err := t.getFileTrunc(dk, truncate)
		if err != nil {
			return err
		}
		if !ok {
			continue
		}

		if !fn(f) {
			return nil
		}
	}
	if err != nil {
		return err
	}
	return dbi.Error()
}

func (t *readOnlyTransaction) withBlocksHash(folder, hash []byte, iterator Iterator) error {
	key, err := t.keyer.GenerateBlockListMapKey(nil, folder, hash, nil)
	if err != nil {
		return err
	}

	iter, err := t.NewPrefixIterator(key)
	if err != nil {
		return err
	}
	defer iter.Release()

	for iter.Next() {
		file := string(t.keyer.NameFromBlockListMapKey(iter.Key()))
		f, ok, err := t.getFile(folder, protocol.LocalDeviceID[:], []byte(osutil.NormalizedFilename(file)))
		if err != nil {
			return err
		}
		if !ok {
			continue
		}
		f.Name = osutil.NativeFilename(f.Name)

		if !bytes.Equal(f.BlocksHash, hash) {
			l.Warnf("Mismatching block map list hashes: got %x expected %x", f.BlocksHash, hash)
			continue
		}

		if f.IsDeleted() || f.IsInvalid() || f.IsDirectory() || f.IsSymlink() {
			l.Warnf("Found something of unexpected type in block list map: %s", f)
Repository: syncthing/syncthing
File: lib/db/schemaupdater.go (Go)

Code before:
			continue
		} else if err != nil {
			return err
		}
		fi := intf.(protocol.FileInfo)
		if fi.Blocks == nil {
			continue
		}
		if err := t.putFile(it.Key(), fi, false); err != nil {
			return err
		}
		if err := t.Checkpoint(); err != nil {
			return err
		}
	}
	it.Release()
	if err := it.Error(); err != nil {
		return err
	}

	db.recordTime(indirectGCTimeKey)

	return t.Commit()
}

func (db *schemaUpdater) updateSchemaTo10(prev int) error {
	// Populates block list map for every folder.

	t, err := db.newReadWriteTransaction()
	if err != nil {
		return err
	}
	defer t.close()

	var dk []byte
	for _, folderStr := range db.ListFolders() {
		folder := []byte(folderStr)
		var putErr error
		err := t.withHave(folder, protocol.LocalDeviceID[:], nil, true, func(fi FileIntf) bool {
			f := fi.(FileInfoTruncated)
			if f.IsDirectory() || f.IsDeleted() || f.IsInvalid() || f.BlocksHash == nil {
				return true
			}

			name := []byte(f.FileName())
			dk, putErr = db.keyer.GenerateBlockListMapKey(dk, folder, f.BlocksHash, name)
			if putErr != nil {
				return false
			}

			putErr = t.Put(dk, nil)

Review comment (suggestion):
```suggestion
func (db *schemaUpdater) updateSchemaTo10(_ int) error {
```

Code after:
	if err != nil {
		return err
	}
	for it.Next() {
		intf, err := t.unmarshalTrunc(it.Value(), false)
		if backend.IsNotFound(err) {
			// Unmarshal error due to missing parts (block list), probably
			// due to a bad migration in a previous RC. Drop this key, as
			// getFile would anyway return this as a "not found" in the
			// normal flow of things.
			if err := t.Delete(it.Key()); err != nil {
				return err
			}
			continue
		} else if err != nil {
			return err
		}
		fi := intf.(protocol.FileInfo)
		if fi.Blocks == nil {
			continue
		}
		if err := t.putFile(it.Key(), fi, false); err != nil {
			return err
		}
		if err := t.Checkpoint(); err != nil {
			return err
		}
	}
	it.Release()
	if err := it.Error(); err != nil {
		return err
	}

	db.recordTime(indirectGCTimeKey)

	return t.Commit()
}

func (db *schemaUpdater) updateSchemaTo10(_ int) error {
	t, err := db.newReadWriteTransaction()
	if err != nil {
		return err
	}
	defer t.close()

	var buf []byte

	for _, folderStr := range db.ListFolders() {
		folder := []byte(folderStr)

		buf, err = t.keyer.GenerateGlobalVersionKey(buf, folder, nil)
Repository: syncthing/syncthing
File: lib/model/folder_sendrecv.go (Go)

Code before:
		}

		fi, ok := snap.GetGlobal(fileName)
		if !ok {
			// File is no longer in the index. Mark it as done and drop it.
			f.queue.Done(fileName)
			continue
		}

		if fi.IsDeleted() || fi.IsInvalid() || fi.Type != protocol.FileInfoTypeFile {
			// The item has changed type or status in the index while we
			// were processing directories above.
			f.queue.Done(fileName)
			continue
		}

		if !f.checkParent(fi.Name, scanChan) {
			f.queue.Done(fileName)
			continue
		}

		// Check our list of files to be removed for a match, in which case
		// we can just do a rename instead.
		key := string(fi.BlocksHash)
		for i, candidate := range buckets[key] {
			if candidate.BlocksEqual(fi) {
				// Remove the candidate from the bucket
				lidx := len(buckets[key]) - 1
				buckets[key][i] = buckets[key][lidx]
				buckets[key] = buckets[key][:lidx]

				// candidate is our current state of the file, where as the
				// desired state with the delete bit set is in the deletion
				// map.
				desired := fileDeletions[candidate.Name]
				if err := f.renameFile(candidate, desired, fi, snap, dbUpdateChan, scanChan); err != nil {
					// Failed to rename, try to handle files as separate
					// deletions and updates.
					break
				}

				// Remove the pending deletion (as we performed it by renaming)
				delete(fileDeletions, candidate.Name)

				f.queue.Done(fileName)
				continue nextFile
			}
		}

		devices := snap.Availability(fileName)
		for _, dev := range devices {

Review comment (suggestion):
This `if` just checks the same thing we used as the key (the `BlocksHash`) so we could drop it

Code after:

		fileName, ok := f.queue.Pop()
		if !ok {
			break
		}

		fi, ok := snap.GetGlobal(fileName)
		if !ok {
			// File is no longer in the index. Mark it as done and drop it.
			f.queue.Done(fileName)
			continue
		}

		if fi.IsDeleted() || fi.IsInvalid() || fi.Type != protocol.FileInfoTypeFile {
			// The item has changed type or status in the index while we
			// were processing directories above.
			f.queue.Done(fileName)
			continue
		}

		if !f.checkParent(fi.Name, scanChan) {
			f.queue.Done(fileName)
			continue
		}

		// Check our list of files to be removed for a match, in which case
		// we can just do a rename instead.
		key := string(fi.BlocksHash)
		for i, candidate := range buckets[key] {
			// Remove the candidate from the bucket
			lidx := len(buckets[key]) - 1
			buckets[key][i] = buckets[key][lidx]
			buckets[key] = buckets[key][:lidx]

			// candidate is our current state of the file, where as the
			// desired state with the delete bit set is in the deletion
			// map.
			desired := fileDeletions[candidate.Name]
			if err := f.renameFile(candidate, desired, fi, snap, dbUpdateChan, scanChan); err != nil {
				l.Debugln("rename shortcut for %s failed: %S", fi.Name, err.Error())
				// Failed to rename, try next one.
				continue
			}

			// Remove the pending deletion (as we performed it by renaming)
			delete(fileDeletions, candidate.Name)

			f.queue.Done(fileName)
			continue nextFile
		}
Repository: syncthing/syncthing
File: lib/model/folder.go (Go)

Code before:
		if file.IsSymlink() {
			objType = "symlink"
		} else if file.IsDirectory() {
			objType = "dir"
		}

		// Two different events can be fired here based on what EventType is passed into function
		f.evLogger.Log(typeOfEvent, map[string]string{
			"folder":     f.ID,
			"folderID":   f.ID, // incorrect, deprecated, kept for historical compliance
			"label":      f.Label,
			"action":     action,
			"type":       objType,
			"path":       filepath.FromSlash(file.Name),
			"modifiedBy": file.ModifiedBy.String(),
		})
	}
}

func (f *folder) forceRescan() {
	paths := make([]string, 0, len(f.forcedRescanPaths))

	f.forcedRescanPathsMut.Lock()
	for path := range f.forcedRescanPaths {
		paths = append(paths, path)
		delete(f.forcedRescanPaths, path)
	}
	f.forcedRescanPathsMut.Unlock()

	batch := newFileInfoBatch(func(fs []protocol.FileInfo) error {
		f.fset.Update(protocol.LocalDeviceID, fs)
		return nil
	})

	snap := f.fset.Snapshot()
	defer snap.Release()

	for _, path := range paths {
		_ = batch.flushIfFull()

		fi, ok := snap.Get(protocol.LocalDeviceID, path)
		if !ok {
			continue
		}
		fi.SetMustRescan(f.shortID)
		batch.append(fi)
	}

	_ = batch.flush()

	_ = f.scanSubdirs(paths)

Review comment (suggestion):
I suggest just throwing away the map and creating a new one after the loop, as I don't think map structures shrink once they've grown.

Code after:
		if file.IsSymlink() {
			objType = "symlink"
		} else if file.IsDirectory() {
			objType = "dir"
		}

		// Two different events can be fired here based on what EventType is passed into function
		f.evLogger.Log(typeOfEvent, map[string]string{
			"folder":     f.ID,
			"folderID":   f.ID, // incorrect, deprecated, kept for historical compliance
			"label":      f.Label,
			"action":     action,
			"type":       objType,
			"path":       filepath.FromSlash(file.Name),
			"modifiedBy": file.ModifiedBy.String(),
		})
	}
}

func (f *folder) handleForcedRescans() {
	f.forcedRescanPathsMut.Lock()
	paths := make([]string, 0, len(f.forcedRescanPaths))
	for path := range f.forcedRescanPaths {
		paths = append(paths, path)
	}
	f.forcedRescanPaths = make(map[string]struct{})
	f.forcedRescanPathsMut.Unlock()

	batch := newFileInfoBatch(func(fs []protocol.FileInfo) error {
		f.fset.Update(protocol.LocalDeviceID, fs)
		return nil
	})

	snap := f.fset.Snapshot()

	for _, path := range paths {
		_ = batch.flushIfFull()

		fi, ok := snap.Get(protocol.LocalDeviceID, path)
		if !ok {
			continue
		}
		fi.SetMustRescan(f.shortID)
		batch.append(fi)
	}

	snap.Release()

	_ = batch.flush()

	_ = f.scanSubdirs(paths)