The National Security Agency has purged hundreds of millions of records logging phone calls and texts that it had gathered from American telecommunications companies since 2015, the agency has disclosed. It had realized that its database was contaminated with some files the agency had no authority to receive.

The agency began destroying the records on May 23, it said in a statement. Officials had discovered “technical irregularities” this year in its collection from phone companies of so-called call record details, or metadata showing who called or texted whom and when, but not what they said.

The agency had collected the data from a system it created under the USA Freedom Act. Congress enacted that law in 2015 to end and replace a once-secret program that had systematically collected Americans’ domestic calling records in bulk. The National Security Agency uses the data to analyze social links between people in a hunt for hidden associates of known terrorism suspects.