WASHINGTON — 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.

The program traces back to a component of the once-secret Stellarwind surveillance program that the Bush administration put in place after the Sept. 11, 2001, attacks. The data collection eventually came to be justified under disputed interpretation of a law known as Section 215 of the Patriot Act and was exposed in 2013 in the leaks by Edward J. Snowden, the former intelligence contractor.